Using PHP namespaces in a Zend Framework (v1) application

心已入冬 提交于 2019-11-28 06:33:16

Actually there is a simple workaround suggested by Dmitry on the ZF issue tracker:

class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
    protected function _initAutoloader()
    {
        $loader = function($className) {
            $className = str_replace('\\', '_', $className);
            Zend_Loader_Autoloader::autoload($className);
        };

        $autoloader = Zend_Loader_Autoloader::getInstance();
        $autoloader->pushAutoloader($loader, 'Application\\');
    }
}

Works like a charm for me!

The standard autloader introduced in 1.12 allows you to use namespaces with minimal effort:

require 'Zend/Loader/AutoloaderFactory.php';
Zend_Loader_AutoloaderFactory::factory([
    'Zend_Loader_StandardAutoloader' => [
        'autoregister_zf' => true,
        'namespaces' => [
            'Application' => '/path/to/Application/src',
        ]
    ]
]);

Now you can use Application\Form\Abc instead of Application_Form_Abc & Application\Model\Xyz instead of Application_Model_Xyz etc.

Directory/File structure examples:

path/to/Application/src/Form/Abc.php

<?php
namespace Application/Form;
class Abc {}

path/to/Application/src/Model/Xyz.php

<?php
namespace Application/Model;
class Xyz {}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!