Creating a controller instance in a Yii structure by directory and namespace

The Yii framework supports modules as well as subdirectories in the controller directory, so the path to a specific action may be

  • /index.php?r=module/controller/action or
  • /index.php?r=subdirectoryInControllerDir/controller/action.

My goal is to have multiple subdirectories in the controller directory. Inside these folders, I created controllers with the same names as the parent using namespaces.

However, if I write

namespace mynamespace;
class MyController extends \MyController {
}

Yii would load MyControllerinsteadmynamespace\MyController;

Any suggestions here?

+3
source share
1 answer

Yii , \application , , . MyController protected/controller/, namespace application\controllers;

<?php
namespace application\controllers;
class MyController extends \CController
{
    // actions
}

MyController protected/controllers/subdir/

<?php
namespace application\controllers\subdir;
class MyController extends \application\controllers\MyController
{
    // actions
}

"subdir/my", CWebApplication::createController() ( ) :

    if(!class_exists($className,false))
        require($classFile);
+   if(!class_exists($className,false))
+       $className = '\\application\\controllers\\' . str_replace('/', '\\', $controllerID . $className);
    if(class_exists($className,false) && is_subclass_of($className,'CController'))
    {
        $id[0]=strtolower($id[0]);
        return array(
            new $className($controllerID.$id,$owner===$this?null:$owner),
            $this->parseActionParams($route),
        );
    }

controllerNameSpace of CWebApplication, hardcoding \\application\\controllers\\.

+1

Source: https://habr.com/ru/post/1783646/


All Articles