我想从另一个控制器扩展控制器
我有控制器“ ProjectController”和“ MembersController”;是否可以从Project控制器扩展Member控制器。
所以我可以得到如下路径:
http://localhost:125/yii2/frontend/web/project/members/view?m=12345
ProjectController
<?php
namespace frontend\controllers;
use Yii;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\AccessControl;
use yii\filters\VerbFilter;
use frontend\models\Project;
/***/
class ProjectController extends Controller
{
public function actionView($p)
{
$model = $this->findProject($id);
return $this->render('/project/view', [
'model' => $model,
]);
}
protected function findProject($id)
{
if (($model = Project::findOne(['project_id' => $id])) !== null) {
return $model;
}
throw new NotFoundHttpException(Yii::t('app', 'The requested page does not exist.'));
}
}
和成员控制器
<?php
namespace frontend\controllers;
use Yii;
use frontend\controllers\ProjectController;
use yii\web\NotFoundHttpException;
use yii\filters\AccessControl;
use yii\filters\VerbFilter;
use frontend\models\Members;
/***/
class MembersController extends ProjectController
{
public function actionView($m)
{
$model = $this->findMembers($m);
return $this->render('/members/view', [
'model' => $model,
]);
}
protected function findMembers($id)
{
if (($model = Members::find()->where(['sproject_id' => $id])->all()) !== null) {
return $model;
}
throw new NotFoundHttpException(Yii::t('app', 'The requested page does not exist.'));
}
}
我使用class MemebrsController extends ProjectController
,但访问此URL时出现 404错误页面
http://localhost:125/yii2/frontend/web/project/members/view?m=123
我的配置文件是
<?php
$params = array_merge(
require __DIR__ . '/../../common/config/params.php',
require __DIR__ . '/../../common/config/params-local.php',
require __DIR__ . '/params.php',
require __DIR__ . '/params-local.php'
);
return [
'id' => 'app-frontend',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'controllerNamespace' => 'frontend\controllers',
'components' => [
'request' => [
'csrfParam' => '_csrf-frontend',
],
'user' => [
'identityClass' => 'frontend\models\User',
'enableAutoLogin' => true,
'identityCookie' => ['name' => '_identity-frontend', 'httpOnly' => true],
],
'session' => [
// this is the name of the session cookie used for login on the frontend
'name' => 'advanced-frontend',
],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'errorHandler' => [
'errorAction' => 'site/error',
],
/* ****************** */
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
'<action:(index|login|logout|signup)>' => 'site/<action>',
],
],
],
'params' => $params,
];
答案 0 :(得分:1)
如果您使用成员扩展了项目控制器,则应使用
http://localhost:125/yii2/frontend/web/members/view?m=123
并检查正确的名称。你有MemebrsController而不是MembersController
答案 1 :(得分:1)
在OOP中,将MemberController
扩展为ProjectController
并不是一个好主意。
对MemberController
进行包装并从Controller
进行扩展,然后将以下规则添加到您的路线中:
'rules' => [
'project/member' => 'member',
// ... Other rules
]