如何在Yii2中分离不同文件中的每个操作

7bsow1i6  于 2022-11-09  发布在  其他
关注(0)|答案(2)|浏览(148)

我是Yii 2框架的新手。为了给我的web应用程序结构化,我想把每个控制器放在一个子文件夹中,并为每个子文件夹中的每个动作制作一个单独的控制器。就像那个!

controllers
      **User**
            IndexController
            EditController
            UpdateController

      **Profile**
            IndexController
            EditController
            UpdateController

在Yii 2里我怎么安排呢。提前谢谢

a7qyws3x

a7qyws3x1#

你的例子是对的。

controllers/user/IndexController.php

views/user/index/index.php

然后在IndexController/EditController/UpdateController中,您有actionIndex,如果您运行domain.com/user/indexdomain.com/user/edit,它将在当前控制器中执行actionIndexIndexControllerEditController

domain.com/user/index = domain.com/user/index/index

and 

domain.com/user/edit = domain.com/user/edit/index
lpwwtiir

lpwwtiir2#

不确定是否有其他更有效的方法,但一个有效的将是以下。

所以,假设我们有一个控制器,我们想把它的一些动作存储到不同的php文件中。

<?php

// frontend\controllers\SiteController.php

namespace frontend\controllers;

use yii\web\Controller;

class SiteController extends Controller {

  public function actions() {
    return [
        'error' => [
            'class' => 'yii\web\ErrorAction',
        ],
        'captcha' => [
            'class' => 'yii\captcha\CaptchaAction',
            'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
        ],
        'hello-world' => [
            'class' => 'frontend\controllers\site\HelloWorldAction',
        ],
    ];
  }

  public function actionIndex() {
      // ...
  }

因此,您可以看到,我们有3个外部操作和一个内部操作。
前两个,是框架的工具,用于生成错误页面和验证码,实际上,它们启发了我的答案。
而第三个,则由我们来定义:

'hello-world' => [
   'class' => 'frontend\controllers\site\HelloWorldAction',
],

因此,我们已经命名了操作,并在一个单独的目录中创建了新的操作类。

<?php

// frontend\controllers\site\HelloWorldAction.php

namespace frontend\controllers\site;

use yii\base\Action;

class HelloWorldAction extends Action {

  public function run($planet='Earth') {
    return $this->controller->render('hello-world', [
        'planet'=>$planet,
    ]);
  }

}

最后,我们的观点是:

<?php

// frontend\views\site\hello-world.php

/* @var $this yii\web\View */

use yii\helpers\Html;

$this->title = 'Hello world page';
?>

<h1>Hello world!</h1>

<p>We're on planet <?php echo Html::encode($planet); ?></p>

并看到它的行动:

更新

在发布答案后,我意识到也许你也可以从另一种技术中受益。
如果您想这样做,前面的答案是好的:Extract actions into individual files .
但是,如果您的应用程序具有一定的大小,也许您应该考虑使用Modules
您可以手动创建它们或使用Gii生成它们:

生成后,请将其包含在您的配置中:

<?php
    ......
    'modules' => [
        'profile' => [
            'class' => 'frontend\modules\profile\Module',
        ],
    ],
    ......

模块就是这样做的,将应用程序逻辑分组到一个目录、控制器、模型、视图、组件等中。
还有两个提示:
现在要访问您的模块,只需访问http://www.your-site.local/profile/default/index,如您所见,它类似于module/controller/action
如果你想在模块中生成动作的链接,你可以:

<?php
echo Url::to([
    'profile/default/index',
    'param'=>'value',
]);
?>

同样,如您所见,我们使用module/controller/action作为路由。
最后,如果你在一个模块中,比如说profile/picture/edit,你想从SiteController链接到Contact页面,你可以这样做:

<?php
echo Url::to([
    '//site/contact', 
    'param'=>'value',
]);
?>

注意路由开头的双斜杠//,如果没有它,它将生成指向当前模块profile/site/contact的url。

相关问题