How to search for all classes found in a tree?

Asked

Viewed 45 times

-2

Imagine the setting where I have the following structure of tree:

  class / conexao / conexao.php
            mvc   / modelos / PessoasModelos.php
                    visoes  / PessoasVisoes.php
                  controles / PessoasControles.php
           util   / classUtilitarios.php

That one __autoloader would look like this:

Function __autoload( $class ) {

   $DS = DIRECTORY_SEPARATOR;

   $paths[] = __DIR__ . $DS  . "class" . $DS  . "conexao" . $DS . $class . ".php";
   $paths[] = __DIR__ . $DS  . "class" . $DS  . "mvc" . $DS  . "modelos" . $DS . $class . ".php";
   $paths[] = __DIR__ . $DS  . "class" . $DS  . "mvc" . $DS  . "visoes" . $DS . $class . ".php";
   $paths[] = __DIR__ . $DS  . "class" . $DS  . "mvc" . $DS  . "controles" . $DS . $class . ".php";
   $paths[] = __DIR__ . $DS  . "class" . $DS  . "classUtilitarios" . $DS . $class . ".php";

foreach ( $paths as $path ) :

    if ( file_exists( $path ) ) require_once $path;

endforeach;

}

Or, in versions plus recent of php:

function autoload( $class ) {

       $DS = DIRECTORY_SEPARATOR;

       $paths[] = __DIR__ . $DS  . "class" . $DS  . "conexao" . $DS . $class . ".php";
       $paths[] = __DIR__ . $DS  . "class" . $DS  . "mvc" . $DS  . "modelos" . $DS . $class . ".php";
       $paths[] = __DIR__ . $DS  . "class" . $DS  . "mvc" . $DS  . "visoes" . $DS . $class . ".php";
       $paths[] = __DIR__ . $DS  . "class" . $DS  . "mvc" . $DS  . "controles" . $DS . $class . ".php";
       $paths[] = __DIR__ . $DS  . "class" . $DS  . "classUtilitarios" . $DS . $class . ".php";

    foreach ( $paths as $path ) :

        if ( file_exists( $path ) ) require_once $path;

    endforeach;

}

spl_autoloader_register("autoload");

But it would force me to create all the paths and, depending on the system, I can have several paths with numerous classes.

Is there a way I don’t need that?

That is, just inform the php that is for him sweep all the subdirectories of index class looking for classes and carry them?

Something like :

    foreach ( $paths as $path ) :
         if(count($path.subpath > 0 ) função recursiva...
        if ( file_exists( $path ) ) require_once $path;

    endforeach;

1 answer

0

I got:

spl_autoload_register(function($class){

    $pasta = "class";
    $listar = new RecursiveDirectoryIterator( $pasta );
    $recursivo = new RecursiveIteratorIterator( $listar );

    foreach ( $recursivo as $obj ):

        if ( $obj->isFile() ) require_once $obj->getPathName();

    endforeach;


});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.