Featured image of post yaf学习笔记

yaf学习笔记

本文阅读量

yaf学习笔记

yaf配置

1
2
# 获取conf/application.ini配置内容
$config = Yaf\Application::app() -> getConfig();

yaf类库加载

自动加载

Http.php

1
2
3
4
5
6
7
<?php
namespace Tool;
class Http{
    public static function getHost(){
        echo $_SERVER['HTTP_HOST'];
    }
}

加载全局

controllers/Index.php

1
2
3
4
5
6
public function indexAction(){
	# 加载类库
	echo Tool\Http::getHost();
	# 如果在 conf/application.ini 没有在[common]设置 application.library.namespace = "Tool"
	# 就会按照php.ini 设置了yaf.library = "/var/libs", 就会上/var/libs/Tool找是否有Http.php文件并加载
}

加载本库

controllers/Index.php

1
2
3
4
5
6
public function indexAction(){
	# 加载类库
	echo Tool\Http::getHost();
	# 如果在 conf/application.ini 在[common]设置 application.library.namespace = "Tool"
	# 就会在项目目录application/library/Tool去查找Http.php并加载
}

手动加载

library/Data/category.php

1
2
3
4
5
class Category{
    public static $data = array(
        'cate'=>'分类'
    );
}

controllers/Index.php

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
# 手动加载一个php文件
public function indexAction(){
    # 按绝对路径加载
    # 如果文件不存在返回false
    if (yaf\Loader::import("/var/www/yaf/Application/library/Data/category.php")){ 
         var_dump(Category::$data);
    }else{
        echo '没有查找到文件';
    }
    
    # 按相对路径加载,相对于library目录
    if(yaf\Loader::import("Data/category.php")){
        var_dump(Category::$data);
    }else{
        echo '没有找到文件';
    }
}

模块和控制器

配置

1
2
3
4
5
application.dispatcher.defaultModule #默认的模块
application.dispatcher.defaultController #默认的控制器
application.dispatcher.defaultAction  #默认方法名
# 定义多模块,一定要定义Index
application.modules = "Index,User"

加载新模块

1
2
3
4
5
# 访问地址/user/index/index 会访问user模块的IndexController里的IndexAction方法
# 修改配置 conf/application.ini
application.modules = "Index,User"

# user模块创建,在application目录下创建modules/User/controller/Index.php

yaf路由

simple模式

在bootstrap中定义

1
2
3
4
5
6
7
8
9
# 在bootstrap的 _initRoute方法中创建
public function _initRoute(Yaf\Dispatcher $dispatcher) {
	//在这里注册自己的路由协议,默认使用简单路由
    $router = $dispatcher -> getInstance() -> getRouter();
	$route = new Yaf\Route\Simple('m','c','a');
	$router -> addRoute('simple',$route);
}

# 之前的 /user/index/index 就可以这样访问 ?m=user&c=index&a=index

在application.ini中配置

在application.ini中配置如下

1
2
3
4
5
6
7
[routes]
routes.simple.type = "simple"
routes.simple.module = "m"
routes.simple.controller = "c"
routes.simple.action = "a"

[develop : common : redis : routes]

修改Bootstrap.php的_initRoute方法

1
2
3
4
5
public function _initRoute(Yaf\Dispatcher $dispatcher) {
	//获取路由对象
    $router = $dispatcher -> getInstance() -> getRouter();
    $router -> addConfig(Yaf\Registry::get("config") -> routes);
}

这时候就可以通过?m=user&c=index&a=index来访问之前的/user/index/index路由

正则模式

在application.ini中配置

在application.ini中配置如下

1
2
3
4
5
6
7
8
9
[routes]
routes.user.type = "regex"
routes.user.match = "#^/([0-9]+)[\/]?#"
routes.user.route.module = "User"
routes.user.route.controller = "Index"
routes.user.route.action = "index"
routes.user.map.1 = userId

[develop : common : redis : routes]

修改Bootstrap.php的_initRoute方法

1
2
3
4
5
public function _initRoute(Yaf\Dispatcher $dispatcher) {
	//获取路由对象
    $router = $dispatcher -> getInstance() -> getRouter();
    $router -> addConfig(Yaf\Registry::get("config") -> routes);
}

user/index/index.php

1
2
3
4
5
6
7
8
9
class IndexController extends Yaf\Controller_Abstract{
    public function IndexAction(){
        echo 'user/index/index';
        $params = $this -> getRequest() -> getParams();
        $userId = $params["userId"];
        echo 'userId:'.$userId;
        return false;
    }
}

这时候就可以通过/12312来访问之前的/user/index/index路由,并且可以获得userId参数

yaf视图

修改拓展名

yaf视图默认拓展名phtml

在application.ini中配置

1
application.view.ext = 'html'

修改模板文件路径

在某个控制器里的init方法中使用

1
2
3
public function init(){
    $this -> getView() -> setScriptPath(APPLICATION_PATH.'/template');
}

渲染模板

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
public function IndexAction(){
    header("Content-type:text/html;charaset=utf8");
    $this -> getView() -> assign("username","用户1");
    $msgTpl = $this -> getView() -> render("User/index.phtml");
    echo $msgTp;
    return false;
}
// 或者
public function IndexAction(){
    header("Content-type:text/html;charaset=utf8");
    $this -> getView() -> assign("username","用户1");
    $this -> getView() -> display("User/index.phtml");
    return false;
}

通过全局禁用模板渲染

在Bootstrap.php中修改

1
2
3
4
public function _initView(Yaf\Dispatcher $dispatcher) {
    //全局禁用模板渲染
    $dispatcher -> getInstance() -> disableView();
}

这样就不用在每个方法中return fasle

请求与响应

请求

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
public function indexAction(){
    # 获取get请求
    $get = $this -> getRequest() -> getQuery();
    # 获取post请求
    $post = $this -> getRequest() -> getPost();
    # 获取上传请求
    $get = $this -> getRequest() -> getFiles();
    # 获取params请求
    $get = $this -> getRequest() -> getParams();
    
    // 获取get/post请求的某个键名
    echo $this -> getRequest() -> get("userId");
    
    // 判断是否是get请求
    if($this -> getRequest() -> isGet()){
        echo '是get请求';
    }else{
        echo '不是get请求';
    }
}

响应

1
2
3
4
5
6
7
public function indexAction(){
    # 在页面显示内容
    $this -> getResponse() -> setBody("contents");
    
    # 在该方法执行完成之后进行响应,如果使用了exit,die就不会响应了
    $this -> getResponse() -> response();
}

可以在Bootstrap.php中设置统一响应

1
2
3
4
5
class Bootstrap extends Yaf\Bootstrap_Abstract {
    public function _initResponse(Yaf\Dispacher $dispacher){
        $dispacher -> getInstance() -> returnResponse(true);
    }
}

模型

模型层定义在models

index.php

1
2
3
4
5
6
7
class IndexController extends Yaf\Controller_Abstract{
    public function IndexAction(){
        $userModel = new UserModel();
        $info = $userModel -> getUserInfo(1);
        var_dump($info);
    }
}

models/user.php

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class UserModel{
    public function getUserInfo($uid){
        // 数据库调用
        $userDao = new Dao\UserModel();
        $userInfo = $userDao -> getUserInfo($uid);
        // 接口调用
        $userInterface = new Interfaces\BbsModel();
        $bbsUserInfo = $userInterface -> getBbsInfo($uid);
        return [$userInfo,$bbsUserInfo];
    }
}

models/Dao/User.php

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
/*
 * 访问数据库入口
 */
namespace Dao;
class UserModel{
    public function getUserInfo($userId){
        $sql = '......';

        # 执行sql
        return '用户信息';
    }
}

models/Interfaces/Bbs.php

1
2
3
4
5
6
7
namespace Interfaces;
class BbsModel{
    public function getBbsInfo($uid){
        // RPC,YAR
        return '用户论坛信息';
    }
}

RPC

rpc远程调用暴露的接口的具体实现

YAR

服务端

application/controllers/Api.php

1
2
3
4
5
6
7
class ApiController extends Yaf\Controller_Abstract{
    // 用户接口
    public function userAction(){
        $application = new Yar_Server(new api\User());
        return false;
    }
}

library/api/User.php

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
namespace api;
class User extends \tool\ApiServer{
    public funciton add(){
        echo __METHOD__;
    }
    public function update(){
        if ($this -> checkSing($params)){
            return $this -> response(0,array(
            	'errorCode' => 'SIGN ERROR',
                'errorInfo' => '签名错误',
            ));
        }
        $userModel = new UserModel();
        $userModel -> updateUser();
    }
}

library/tool/ApiServer.php

1
2
3
4
5
6
# 服务器端api接口签名验证
class ApiServer extends Yaf\Controller_Abstract{
    public function checkSing($params){
        // 校验签名..
    }
}

客户端

application/controller/index.php

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class IndexController extends Yaf\Controller_Abstract{
    public function indexAction(){
        try{
            $client = new Yaf_Client("http://yaf-demo.com/Api/User");
            echo 'result:'.$client->update();
        }catch(Exception $e){
            echo "Exception:".$e->getMessage();
        }
        return false;
    }
}
# 同样我们可以将client进行封装
class IndexController extends Yaf\Controller_Abstract{
    public function indexAction(){
        try{
            $client = new tool\ApiClient("http://yaf-demo.com/Api/User");
            echo 'result:'.$client->update();
        }catch(Exception $e){
            echo "Exception:".$e->getMessage();
        }
        return false;
    }
}

cli模式

作用

定时任务,守护进程

在application同级目录下创建一个cli/cli.php

请求方式: php cli.php位置 request_uri="/cli/test/run"

1
2
3
4
5
6
7
8
9
header("Content-type:text/html;charset=utf8");
ini_set("display_errors",1);
error_reporting(E_ALL);
date_default_timezone_set('Asia/Shanghai');
define('APPLICATION_PATH', dirname(__DIR__));
$application = new Yaf\Application( APPLICATION_PATH . "/conf/application.ini");
$application->bootstrap();
$application->getDispatcher()->dispatch(new Yaf\Request\Simple());
$application->run();
使用 Hugo 构建
主题 StackJimmy 设计