BenMorel
BenMorel

Reputation: 36484

Using PHP namespaces in a Zend Framework (v1) application

Is it possible in the current stable version of the Zend Framework (1.11), to work with application classes using PHP namespaces?

Application\Form\Abc instead of Application_Form_Abc
Application\Model\Xyz instead of Application_Model_Xyz
etc.

Starting from v1.10, ZF supports autoloading namespaces, and it's working fine when including namespaced libraries, but I was unsuccessful when trying to do the same job with application classes.

Upvotes: 13

Views: 10516

Answers (3)

iaskakho
iaskakho

Reputation: 11

For those wanting your controllers to work and not just the forms and models :) Take a look at the Zend\Controller\Dispatcher\Standard.php:174

public function formatClassName($moduleName, $className)

You would need to swap the _ with "\" as well in order to get the correct class name.

Upvotes: 0

Gerard Roche
Gerard Roche

Reputation: 6361

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 {}

Upvotes: 6

BenMorel
BenMorel

Reputation: 36484

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!

Upvotes: 8

Related Questions