Loading controllers

I am writing a system using the MVC pattern. The question arose about how to load controllers.
There is an option to use autoload, but then you have to limit yourself to one directory, but I wanted to separate some modules logically. Or you can create your own loader and explicitly call it, and then it will be possible to load it from any directories. So how is it better?
Reject autoload and explicitly load or discard subdirectory structure and use autoload?


Answer 1, authority 100%

I think autoloadis preferable – you can “forget” about some things (in a good way), everything will be done by itself. As a result, there are fewer errors.

And the directory structure – it already depends on the organization of the mind. 🙂 For some (me) automation is more important than a tree structure, for others it is visual order and structure.

P.S. What framework do you use?


Answer 2

Take the Kohana and don’t suffer!
IMHO, you reinvent your bicycle with square wheels and a pin instead of a saddle!


Answer 3

With regards to limiting yourself to one directory, you can do something like this:

<?php
/*
 * bootstrap.php
 */
ini_set( "include_path",
        implode( PATH_SEPARATOR,
                array(
                        ini_get("include_path"),        # default include path
                        dirname( __FILE__ ),
                )
        )
);
function __autoload( $name ) {
        if( preg_match_all( "/([A-Z]*[^A-Z]*)/", $name, $match, PREG_SET_ORDER ) ) {
                $words = array();
                foreach ( $match as $re ) {
                        if( !empty( $re[1] ) ) {
                                $words[] = strtolower( $re[1] );
                        }
                }
                $name = implode( DIRECTORY_SEPARATOR, $words ) . '.php';
        }
        require_once( $name );
}

Actually, all files will be stored in the directory tree where bootstrap.php is located at the root. Or if you refuse the first ini_set, then where indicated in the include_path.

How to use it:

<?php
/*
 * index.php
 */
require_once("{root}/bootstrap.php");
class MyController extends BaseController {
    # ...
    function __construct() {
        $this->dbh = new ServerDAO(...)
    }
}

Accordingly, the BaseController class will be taken from the base/controller.php file, and for the ServerDAO class, the server/dao.php file will be loaded

Directory tree for this example:

  • {root}/
  • {root}/bootstrap.php
  • {root}/base/controller.php
  • {root}/server/dao.php