Yii2 新增service层
第一种方法呢 ,就是 像 Yii::$app 中的 $app一样配置一个静态变量 $serivce
还有就是建一个service 组件(component)的方法 相关配置如下
│ ├─common │ │─config │ │ bootstrap.php │ │ main.php │ └─components │ │ Service.php │ │ │ ├─services │ Application.php
单独建立services文件夹用来存放服务层文件
config里面的 bootstrap.php 加上路径
Yii::setAlias('@services', dirname(dirname(__DIR__)) . '/services');
config 里main.php配置service组件
'components' => [ ...... /** ------ 服务层 ------ **/ 'services' => [ 'class' => 'services\Application', ], ......
service.php
<?php namespace common\components ; use Yii ; use yii\base\Component; use yii\base\InvalidConfigException; class Service extends Component{ public $childService; /** * 已实例化的子服务 * * @var */ protected $_childService; /** * 获取 services 里面配置的子服务 childService 的实例 * * @param $childServiceName * @return mixed * @throws InvalidConfigException */ protected function getChildService($childServiceName) { if (!isset($this->_childService[$childServiceName])) { $childService = $this->childService; if (isset($childService[$childServiceName])) { $service = $childService[$childServiceName]; $this->_childService[$childServiceName] = Yii::createObject($service); } else { throw new InvalidConfigException('Child Service [' . $childServiceName . '] is not find in ' . get_called_class() . ', you must config it! '); } } return $this->_childService[$childServiceName] ?? null; } /** * @param string $attr * @return mixed * @throws InvalidConfigException */ public function __get($attr) { return $this->getChildService($attr); } }
Application.php 其实就是注册服务
<?php namespace services; use common\components\Service ; class Application extends Service { // service 层的使用方法 // public $childService = [ // 'example' => [ // 'class' => 'services\example\ExampleService', // // 子服务 // 'childService' => [ // 'rule' => [ // 'class' => 'services\example\rule\RuleService', // ], // ], // ], // ]; //$service = Yii::$app->services->example->index(); //$childService = Yii::$app->services->example->rule->index(); /** * @var array */ public $childService = []; }
更多内容请付费阅读
评论区
请登陆 后评论!