开发者

Best way to autoload a model class in specific folder HMVC

开发者 https://www.devze.com 2023-03-26 04:14 出处:网络
I\'m currently writing my own PHP framework as a learning exercise using the HMVC design pattern. It all works :), but I\'ve read many times that it\'s a bad habit to refer to static classes in your P

I'm currently writing my own PHP framework as a learning exercise using the HMVC design pattern. It all works :), but I've read many times that it's a bad habit to refer to static classes in your PHP code, which is exactly what I'm doing in my autoload function:

function __autoload($className) {
    $path = SERVER_ROOT . DS . 'applications' . DS . Dispatcher::getApplicationName() . DS . 'models' . DS . 'class.' . strtolower($className) . '.php';

    if (file_exists($path)) {
        require_once($path);
    } else {
        throw new Exception('Can\'t find a model at "' . $path . '".');
    }
}

As you can see I get the current application using the static call Dispatcher::getApplicationName(), which is bad according to many people since it introduces dependencies. I can also get the applicationName using debug_backtrace(), since the class that initiates the model contains the ApplicationName as a property. Is that better, or are there other alternatives I haven't thought of?

Thanks!

Edit: forgot to mention that there's another problem with the above code: the controller's application does not always equal the dispatcher's application, since I'm using the HMVC design pattern (so controllers are called inside controllers). This can only be fixed using debug_backtrace.

Edit: Instead of Dispatcher::getApplicationName() I now use Request::getCurrentApplicationName(). It now works again, because my request class saves all applications. Is this better, or is there a better way?

<?php

class Request {
    private static $_controllers = array();
    private static $_applicationsNames = array();

    public static function _getCurrentApplicationName() {
        return end(self::$_applicationsNames);
    }

    public static function _load($applicationName, $controllerName, $methodName) {
        // Add the application the the array (for autoloading).
        self::$_applicationsNames[] = $applicationName;

        // Check if the controller has alr开发者_运维技巧eady been instantiated.
        if (!isset(self::$_controllers[$applicationName . DS . $controllerName])) {
            require_once(APPLICATIONS_ROOT . DS . $applicationName . DS . 'controllers' . DS . 'class.' . $controllerName . '.php');
            self::$_controllers[$applicationName . DS . $controllerName] = new $controllerName($applicationName);
        }

        // Get the user arguments.
        $arguments = array_slice(func_get_args(), 3);

        // Call the method.
        $result = call_user_func_array(array(self::$_controllers[$applicationName . DS . $controllerName], $methodName), $arguments);

        // Remove the last value from the applications array.
        array_pop(self::$_applicationsNames);
    }
}


Can't you just set static member of autoload class during startup containing all necessary information?

debug_backtrace() cannot be reliable source of information. What if somebody would like to use your libraries and your autoloader, but without one of the starting layers? Would it be possible that way?

All data used by class/function should be placed within that class or as parameter for the function. Because autoloader can be any callback, you can do something like this:

class FrameworkAutoloader
{
    public $appName;
    public $path;

    public function setAppName($name) { $this->appName = $name; }
    public function setPath($path) { $this->path= $path; }


    function __autoload($className) {
        $path = $this->path. DS . 'applications' . DS . $this->appName . DS . 'models' . DS . 'class.' . strtolower($className) . '.php';

        if (file_exists($path)) {
             require_once($path);
        } else {
             throw new Exception('Can\'t find a model at "' . $path . '".');
        }
    }
}

$autoloader = new FrameworkAutoloader();
$autoloader->setAppName('asd'); //you can also apply those within constructor, but leave setters
$autoloader->setPath('asd');
spl_autoload_register(array($autoloader, '__autoload'));

That's all. You will be able to set path and appname dynamically - just by changing object's variables using setters.

Why we should do that this way? In this code there is no "magic" going around. You can write documentation using PHPDOC to every function and user will know where all params come from. Another advantage is that I can use this code anywhere, I don't need to know, that the class uses Dispatcher::getApplicationName().


I'd consider setting an APPLICATION_ROOT definition in whatever file bootstraps the application. That would be a useful thing to have available all the time, not just in __autoload.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号