统一控制权
主要集成一般的方法
==原则是: 能减少代码量,经常使用==
- 在根目录新建文件夹common
- 在上面的common目录建立一个组件 文件夹命名为
components
- 在components文件夹里面建立文件
BaseWebController.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
| namespace app\common\components;
use app\web\Controller;
class BaseWebController extends Controller { public $enableCsrfValidation = false;
public function get($key,$default_val=''){ return \Yii::$app->request->get($key,$default_val); }
public function post($key,$default_val){ return \Yii::$app->request->post($key,$default_val); }
public function setCookie($name,$value,$expire=0){ $cookie = \Yii::$app->response->cookies; $cookie->add(new \yii\web\Cookie([ 'name' => $name, 'value' => $value, 'expire' => $expire ])); }
public function getCookie($name,$default_val=''){ $cookies = \Yii::$app->request->cookies; return $cookies->getValue($name,$default_val); }
public function removeCookie($name){ $cookies = \Yii::$app->response->cookies; $cookie->remove($name); }
public function renderJson($data=[],$msg='ok',$code=200){ header("Content-type:application/json");
echo json_encode([ 'code' => $code, 'msg' => $msg, 'data' => $data, 'req_id' => uniqid() ]); } }
|
然后把controllers下面里面的文件继承类名称都改成BaseWebController
1 2 3 4 5 6 7 8 9 10 11
| namespace app\controllers;
use app\common\components\BaseWebController;
class DefaultController extends BaseWebController{
public function actionIndex(){
return $this->render("index"); } }
|
统一链接管理
- 在根目录新建文件夹common
- 在上面的common目录建立一个服务文件夹命名为
services
- 在 services 文件夹里面建立文件
UrlService.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| namespace app\common\services;
use yii\helpers\Url;
class UrlService { public function buildWebUrl($url,$params=[]){ $domain-config = \Yii::$app->params['domain']; $path = Url::toRoute(array_merge( [$path],$params )) return $domain_config['web'].$path; }
public static function buildMUrl($url,$params=[]){ $domain-config = \Yii::$app->params['domain']; $path = Url::toRoute(array_merge( [$path],$params )) return $domain_config['m'].$path; }
public static function buildWwwUrl($url,$params=[]){ $domain-config = \Yii::$app->params['domain']; $path = Url::toRoute(array_merge( [$path],$params )) return $domain_config['www'].$path; }
public static function buildNullUrl(){ return 'javascript:void(0);'; }
}
|
然后去前端view页面里面去修改如下
1 2 3 4 5
| <?php use app\common\services\UrlService; ?> <img src="<?=UrlService::buildWwwUrl("/images/common/grcode.jpg");?>">
|
在config/params
配置项里配置域名名称
1 2 3 4 5 6 7
| return [ "domain" => [ 'www' => 'http://wx.sonlq.com'; 'web' => 'http://wx.sonlq.com/web'; 'm' => 'http://wx.sonlq.com/m'; ] ];
|