天天看点

yaf使用命名空间,并使用smarty模板引擎

最近准备自己写一个博客系统,由于使用过laravel,thinkphp,cakephp,ci等框架,最后决定使用yaf,原因就是速度快,其他框架虽然易用,但是qps真的很低。我的项目也比较简单,增删改查。

于是决定使用yaf,使用swoole作为http服务器,引用一些常用的包,例如smarty,medoo操作数据库。

首先需要明确的几个问题:

1.yaf不支持完整的psr,这个很想吐槽,但是鸟哥不愿意改啊,可能是因为改动太大,相当于从新造了一个yaf,不然该叫yafyaf,yet another yaf 了。

2.现在都使用composer来进行包管理,让yaf支持的话,也需要做一些改动,什么都自己写太麻烦了。

于是准备做下面几件事情:

第一步开启yaf命名空间支持,为了方便使用其它composer包,安装smarty包;

composer require smarty/smarty      

修改php的配置文件:

extension=yaf
yaf.use_namespace=1  #开启命名空间
yaf.lowcase_path=1  #路径全部转换为小写
yaf.cache_config=1      

首先修改配置文件:

[common]
application.directory = APPLICATION_PATH  "/application"
application.dispatcher.catchException = TRUE
application.view.ext=tpl  #设置模板文件后缀,供smarty使用

[product : common]

database.database_type='mysql'
database.database_name='blog'
database.server='xxx'
database.username='user'
database.password='xxx'
database.charset='utf8mb4'
database.collation='utf8mb4_general_ci'
database.port=3306

#设置smarty相关的参数
smarty.left_delimiter   = "{{ "
smarty.right_delimiter  = " }}"
smarty.template_dir     = APPLICATION_PATH "/application/views/"
smarty.compile_dir      = APPLICATION_PATH "/application/cache/compile"
smarty.cache_dir        = APPLICATION_PATH "/application/cache/"
smarty.caching          = 0      

bootstrap.php里面加载comoser的autoload文件。

public function _initLoad()
    {
        Yaf\Loader::import(APPLICATION_PATH . '/application/vendor/autoload.php');
    }      

第二步修改原始代码,使其符合命名空间的调用;

参考:https://www.laruence.com/2020/04/18/5832.html#comment-147520

就是需要把原来的Yaf_替换为Yaf\,使用编辑器全局替换即可。

第三步:写view的适配器,实现Yaf\View_Interface接口

必须实现下面这几个方法。

public string render( string $view_path ,
array $tpl_vars = NULL );
public boolean display( string $view_path ,
array $tpl_vars = NULL );
public boolean assign( mixed $name ,
mixed $value = NULL );
public boolean setScriptPath( string $view_directory );
public string getScriptPath( void ); #这个地方比较坑,yaf3.2把这里改成需要参数了,但是文档还没改,我下面的方法是该整正之后的。      
<?php

class SmartyAdapter implements Yaf\View_Interface
{
    /**
     * Smarty object
     * @var Smarty
     */
    public $_smarty;

    /**
     * Constructor
     *
     * @param string $tmplPath
     * @param array $extraParams
     * @return void
     */
    public function __construct($tmplPath = null, $extraParams = array())
    {
        Yaf\Loader::import(APPLICATION_PATH . '/application/vendor/smarty/smarty/libs/bootstrap.php');
        $this->_smarty = new Smarty();
        if (null !== $tmplPath) {
            $this->setScriptPath($tmplPath);
        }
        foreach ($extraParams as $key => $value) {
            $this->_smarty->$key = $value;
        }
    }

    /**
     * Return the template engine object
     *
     * @return Smarty
     */
    public function getEngine()
    {
        return $this->_smarty;
    }

    /**
     * Set the path to the templates
     *
     * @param string $path The directory to set as the path.
     * @return void
     */
    public function setScriptPath($path)
    {
        if (is_readable($path)) {
            $this->_smarty->template_dir = $path;
            return;
        }

        throw new Exception('Invalid path provided');
    }
    /**
     * Retrieve the current template directory
     *
     * @return string
     */
    public function getScriptPath($request = null)
    {
        return $this->_smarty->template_dir ?? null;
    }

    /**
     * Alias for setScriptPath
     *
     * @param string $path
     * @param string $prefix Unused
     * @return void
     */
    public function setBasePath($path, $prefix = 'Zend_View')
    {
        return $this->setScriptPath($path);
    }

    /**
     * Alias for setScriptPath
     *
     * @param string $path
     * @param string $prefix Unused
     * @return void
     */
    public function addBasePath($path, $prefix = 'Zend_View')
    {
        return $this->setScriptPath($path);
    }

    /**
     * Assign a variable to the template
     *
     * @param string $key The variable name.
     * @param mixed $val The variable value.
     * @return void
     */
    public function __set($key, $val)
    {
        $this->_smarty->assign($key, $val);
    }

    /**
     * Allows testing with empty() and isset() to work
     *
     * @param string $key
     * @return boolean
     */
    public function __isset($key)
    {
        return (null !== $this->_smarty->get_template_vars($key));
    }
    /**
     * Allows unset() on object properties to work
     *
     * @param string $key
     * @return void
     */
    public function __unset($key)
    {
        $this->_smarty->clear_assign($key);
    }

    /**
     * Assign variables to the template
     *
     * Allows setting a specific key to the specified value, OR passing
     * an array of key => value pairs to set en masse.
     *
     * @see __set()
     * @param string|array $spec The assignment strategy to use (key or
     * array of key => value pairs)
     * @param mixed $value (Optional) If assigning a named variable,
     * use this as the value.
     * @return void
     */
    public function assign($spec, $value = null)
    {
        if (is_array($spec)) {
            $this->_smarty->assign($spec);
            return;
        }
        $this->_smarty->assign($spec, $value);
    }

    /**
     * Clear all assigned variables
     *
     * Clears all variables assigned to Zend_View either via
     * {@link assign()} or property overloading
     * ({@link __get()}/{@link __set()}).
     *
     * @return void
     */
    public function clearVars()
    {
        $this->_smarty->clear_all_assign();
    }

    /**
     * Processes a template and returns the output.
     *
     * @param string $name The template to process.
     * @return string The output.
     */
    public function render($name, $value = null)
    {
        return $this->_smarty->fetch($name);
    }

    public function display($name, $value = null)
    {
        echo $this->_smarty->fetch($name);
    }
}      
public function _initView(Yaf\Dispatcher $dispatcher)
    {
        $smartyConfig = Yaf\Registry::get("config")->get("smarty");

        //在这里注册自己的view控制器,例如smarty,firekylin
        $smarty = new SmartyAdapter(null, $smartyConfig);
        $dispatcher::getInstance()->setView($smarty);
    }      

第四步:修改bootstrap里面的iitView方法,更改samrty为view的渲染引擎

D:\phpStudy\PHPTutorial\WWW\yaf_test\application\Bootstrap.php
public function _initView(Yaf\Dispatcher $dispatcher)
    {
        $smartyConfig = Yaf\Registry::get("config")->get("smarty");

        //在这里注册自己的view控制器,例如smarty,firekylin
        $smarty = new SmartyAdapter(null, $smartyConfig);
        $dispatcher::getInstance()->setView($smarty);
    }      

第五步:在模板里使用smarty渲染

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>
  {{ foreach from=$list item=item key=key }}
    {{ $item['id'] }} ==  {{ $item['name'] }}
    <br>
  {{ /foreach }}

</body>
</html>      

控制器代码:

<?php

use \Yaf\Controller_Abstract as Controller;

/**
 * @name IndexController
 * @author admin
 * @desc 默认控制器
 * @see http://www.php.net/manual/en/class.yaf-controller-abstract.php
 */
class IndexController extends Controller
{
    /**
     * 默认初始化方法,如果不需要,可以删除掉这个方法
     * 如果这个方法被定义,那么在Controller被构造以后,Yaf会调用这个方法
     */
    public function init()
    {
        if (wantJson()) {#判断请求是否是需要json数据返回
            Yaf\Dispatcher::getInstance()->disableView();
        }
    }

    /**
     * 默认动作
     * Yaf支持直接把Yaf\Request_Abstract::getParam()得到的同名参数作为Action的形参
     * 对于如下的例子, 当访问http://yourhost/yaf_skeleton/index/index/index/name/admin 的时候, 你就会发现不同
     */
    public function indexAction($name = "Stranger")
    {
        //1. fetch query
        $get = $this->getRequest()->getQuery();
        //2. fetch model
        $user = new UserModel();
        $list = $user->list();
        $this->getView()->assign(compact('list'));
    }
}      

效果如下:

yaf使用命名空间,并使用smarty模板引擎

到这里就完成了samrty的集成。