在Yii框架之外的外部PHP控制器中使用Yii1.x模型函数

问题描述 投票:0回答:1

我正在使用Yii1旧网站。与某些外部PHP控制器链接。这些外部控制器提供了在2个不同应用程序之间使用的一些通用功能。我在Yii模型中有一个要在外部PHP控制器之一中使用的函数,有没有办法做到这一点?当前,这是通过在PHP外部控制器中重写MySQL查询来完成的,但我不想遵循这种la脚的做法。

我找到了此链接,我可以从外部访问Yii,但这仍然不是很有帮助。 Using Yii in 3rd-Party Systems

这是我的代码示例:

namespace main\Helpers;

require_once('path/to/yii.php');


Class HelperClass {
 public static function yiisupport($id){
 //   I am able to access Yii variables using
     \Yii::app()->name
 // But how to access the yii model or controller functions? I need something like the follwoing
  $model =  \Yii::app()->YiiModel::model()->findByPK($id);
 }
}

有人可以帮忙吗?

php yii
1个回答
0
投票

您需要首先创建Yii应用程序(使用配置文件路径)以访问其模型和控制器,如documentation中所述。然后,您可以在外部应用程序中访问任何模型类,就像在Yii应用程序中访问它一样,并且可以使用如下所示的控制器操作;

$controller = new \YOURController('ACTION_NAME');
$controller->ACTION_NAME();

如果您已经在配置文件中导入了模型/控制器,那么您将不需要导入任何类,但是如果没有,那么您可以如下导入特定的模型/控制器;

\Yii::import('application.models.MODEL_NAME');
\Yii::import('application.controllers.CONTROLLER_NAME');

检查以下示例;

namespace main\Helpers;

require_once('path/to/yii.php');
\Yii::createWebApplication('path/to/config.php');

Class HelperClass {
    public static function yiisupport($id){
        // Access Yii variables
        \Yii::app()->name;

        // Access yii model
        $model = \YiiModel::model()->findByPK($id);

        // Access yii controller and its actions
        $controller = new \YiiController('actionCreate');
        $controller->actionCreate();
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.