简体   繁体   中英

Adding PHP namespaces into an existing ZF1 application

I'm trying to integrate PHP namespaces into an existing Zend Framework project (v1.12). When I add namespacing at the top of a working controller, it doesn't work anymore and the application throws an Invalid controller class error. Here's my controller definition :

namespace MyProject\Controller;

use MyProject\Controller\MyRestController;

class MyFooController extends MyRestController
{
}

and the init method within the Bootstrap.php :

protected function _initAutoload()
{
    $autoloader = Zend_Loader_Autoloader::getInstance();
    $autoloader->registerNamespace('MyProject');
    return $autoloader;
}

Just a guess (have not used ZF for quite some time): Zend will not accept any class as a controller, just those extended from the framework's base controller class. As you don't extend from the frameworks base controller class you see the error.

If that is the reason, take care you initially extended from the base framework controller class or you implemented the needed interface.

namespace MyProject\Controller;

class MyRestController extendes Zend_Framework_Base_Controller_Class_Name_Here
{
    ...

ps the use MyProject\\Controller\\MyRestController; looks superfluous as that class is in that namespace already. Let's review your code:

namespace MyProject\Controller;

This sets the namespace of the file. That means, non-FQCN will resolve into it. For example:

new MyRestController();

Resolves to the following FQCN:

new MyProject\Controller\MyRestController

Which - oha! - is exactly what you wrote in use:

use MyProject\Controller\MyRestController;

Which means, that this use clause is superfluous, the extend in:

class MyFooController extends MyRestController

Would go to it anyway at first. Because it's the same namespace.

I am facing similar problem now. For me this looks like that Zend cannot properly resolve namespaced controller name. So when I put for example IndexController into namespace \\Basic\\Controller, it will be not loaded because Zend want to load \\IndexController class, which does not exist.

I am thinking about extending standard zend router class, which has method getControllerName.

Then I can set this in bootstrap by:

$router = new \My\Namespaced\Router();

$front = Zend_Controller_Front::getInstance();
$front->setRouter($router);

I didn't tried that code yet but this should work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM