4
4

More than 5 years have passed since last update.

[ZF1] application.iniにリソースオートローダの設定を記述する

Posted at

ディレクトリが以下のように構成されている場合、

application/
    configs/
        application.ini
    controllers/
    models/
        User.php (Model_User)
        User/
            Abstract.php (Model_User_Abstract)
    plugins/
    services/
        User.php (Service_User)

Bootstrapなどで

Bootstrap.php
public function _initAutoloader() {
    $autoloader = new Zend_Loader_Autoloader_Resource(
        'basePath'  => APPLICATION_PATH,
        'namespace' => '',
    ));
    $autoloader
        ->addResourceType('Model', 'models/', 'Model')
        ->addResourceType('Service', 'services/', 'Service');
}

のようにリソースオートローダを初期化すれば、models/User.phpmodels/User/Abstract.phpservices/User.phpをオートロードできる。

これだけでも別にOKだけど、ディレクトリの場所は簡単に変更できるようにしておきたい。

なのでリソースプラグインを利用してapplication.iniから設定を読み込み、リソースオートローダを初期化する。

application/plugins/Autoloader.php
<?php

class Plugin_Autoloader extends Zend_Application_Resource_ResourceAbstract {

    public function init() {
        $options = $this->getOptions();

        $autoloader = new Zend_Loader_Autoloader_Resource(array(
            'basePath'  => $options['basePath'],
            'namespace' => $options['namespace'],
        ));
        unset($options['basePath']);
        unset($options['namespace']);

        foreach ($options as $prefix => $path) {
            $autoloader->addResourceType($prefix, $path, $prefix);
        }
                return $autoloader;
    }

}
application/configs/application.ini
pluginPaths.Plugin = APPLICATION_PATH "/plugins"
resources.autoloader.basePath  = APPLICATION_PATH
resources.autoloader.namespace = ""
resources.autoloader.Model     = "models"
resources.autoloader.Service   = "services"

ちなみに(Table Data GatewayとかData MapperとかServiceとかの)使い回し可能なインスタンスを一々生成するのは無駄なので、たとえばService_Userを呼び出す場合、

$autoloader = Zend_Controller_Front::getInstance()->getParam("bootstrap")->getResource("autoloader");
$userService = $autoloader->load('User', 'service');

とする(Zend_Loader_Autoloader_ResourceはRegistryおよびFactoryとして動作する)。

記述が長いのでZend_Registryあたりに$autoloaderを保存しとくと楽かも。

4
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4