wuye1200 / blog

alber blog
0 stars 0 forks source link

[php] YII2学习 #10

Open wuye1200 opened 6 years ago

wuye1200 commented 6 years ago

命名空间

namespace 指定当前文件的命名空间

例如

// a.php
namespace user\a
class A{
}
// b.php
namespace user\b
class A{
}

use

//定义class的命名空间默认为 user\demo
use\user\a A;
//as 别名
use\user\b A as B;
$classA= new A();
$classB= new B();
//全局类 顶层类
$classC= new \A();
wuye1200 commented 6 years ago

Controller

namespace app\controller;
use yii\web\Controller;
class HelloController extends Controller {
      public function actionIndex(){
            echo 'hi';
      }
}

请求组件

$request = \YII: $app-> request;
$request = request -> get('id'); //获取url里面id参数 get方式
$request = request -> post('id'); //获取url里面id参数 post方式
if( $request -> isGet) //判断是否为get方式
api [http://www.yiichina.com/doc/api/2.0/yii-web-request ]

响应组件

$res = \YII::$app->response;
$res->statusCode = '400';
$res->headers->add('prama','no-cache');
$this->redirect('http://www.baidu.com');//重定向
$res->headers->add('content-disposition',''attachment;filename="a.png"');//下载文件
$res->sendFile('./test.txt');//下载文件

session

$session = \YII:$app->session;
$session->open();
if($session->isActive); //是否开启
$session->set(key,value);
$session->get(key)

cookies

$cookies  = \YII:$app->respones->cookies;
//设置
$data = array('name'=>‘user’,'value'=>'test');
$cookies -> add(key,value);
$cookies->remove('id');

获取cookies

$cookies = \YII::$app->request->cookies;
$cookies->getValue('user');
wuye1200 commented 6 years ago

视图

return $this - >renderPartial('index.php')//渲染视图
$this->rend('index');//