CI框架整合yar

第一步:在CI框架中libraries目录下建立yar.php 文件

内容:

<?php
/**
*  yar 接口
*/
class Yar
{
    /**
     * 构造函数
     *
     * @return void
     * @throws Exception
     * @access public
     */
    public function __construct ()
    {
    }
    /**
     * 接口
     *
     * @return void
     * @throws Exception
     * @access public
     */
    public function yarApi ( array $condition )
    {
        $default = array(
// 服务器地址           'url'=>'http://admin.com/rpc/',
            'url'=>'http://localhost/rpc/',
            'model'=>'',//model名称
            );
        $condition = array_merge($default,$condition);
        return new Yar_Client("{$condition['url']}{$condition['model']}");
    }



}

2.在配置文件中添加yar让CI 自动加载

config目录下autoload.php文件

修改:

$autoload['libraries'] = array('yar');

3.在api服务端也是CI框架建立Rpc.php控制器

内容:

<?php
/**
 * rpc接口
 * Created by PhpStorm.
 * User: hteen
 * Date: 16/6/24
 * Time: 下午4:39
 */
class Rpc extends CI_Controller {


    public function index( $model ){

        if (!$this->_auth())
            show_error('error',500);

        try {
            $this->load->model($model);
        }catch ( Exception $e ){

            log_message('error','rpc load model error , model name is '.$model);
            show_error('load model error',500);
        }

        $service = new Yar_Server( new $model );
        $service->handle();
    }

    /**
     * 权限认证
     * @author hteen
     * @return bool
     */
    private function _auth(){

        // TODO:RPC权限验证
        return true;
    }

}

 

 

4.使用yar

在控制器中使用yar 访问api接口

例如:

//实例化对象
        $ActivityModel = $this->yar->yarApi(['model' => 'ActivityModel']);
//调用方法
        $active_info = $ActivityModel->getinfo($id);

 

posted @ 2016-12-27 15:21  奋进程序猿  阅读(488)  评论(0编辑  收藏  举报