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'));
    }
}

效果如下:

在这里插入图片描述
到这里就完成了samrty的集成。

代码地址:
https://github.com/ShuiPingYang/yaf-blog/tree/add_smarty

集成swoole作为http服务:https://github.com/LinkedDestiny/swoole-yaf

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Yaf 是一个高效的 PHP 框架,它支持多种缓存机制,其中之一便是 Memcache。下面以一个简单的示例来说明如何在 Yaf使用 Memcache。 首先,确保已经安装了 Memcache 扩展,并在 php.ini 文件中启用了该扩展。 接下来,在 Yaf 的配置文件中添加以下代码: ```php // application.ini [product] application.directory = APP_PATH "/application/" ; Memcache 缓存配置 cache.memcache.enable = true cache.memcache.server = "127.0.0.1" cache.memcache.port = 11211 cache.memcache.prefix = "yaf_" ``` 这里定义了一个名为 `cache.memcache` 的缓存配置,启用了 Memcache 缓存,并指定了 Memcache 服务器的地址、端口和缓存前缀。 接着,在 Yaf 的 Bootstrap 文件中添加以下代码: ```php // Bootstrap.php class Bootstrap extends Yaf_Bootstrap_Abstract { public function _initCache() { // 获取缓存配置 $config = Yaf_Application::app()->getConfig()->cache->memcache; // 初始化 Memcache $cache = new Memcache(); $cache->connect($config->server, $config->port); // 将 Memcache 实例注册到 Yaf 的全局注册表中 Yaf_Registry::set("cache", $cache); } } ``` 这里通过 Yaf 的 Bootstrap 机制来初始化 Memcache,将其实例注册到 Yaf 的全局注册表中,方便在整个应用程序中使用。 最后,可以在 Yaf 的控制器中使用 Memcache。例如: ```php // IndexController.php class IndexController extends Yaf_Controller_Abstract { public function indexAction() { // 从 Yaf 的全局注册表中获取 Memcache 实例 $cache = Yaf_Registry::get("cache"); // 尝试从缓存中获取数据 $data = $cache->get("example"); if ($data === false) { // 如果缓存中不存在,则从数据库或其他数据源获取数据 $data = "Hello, world!"; // 将数据存入缓存中 $cache->set("example", $data); } // 输出数据 echo $data; } } ``` 这里通过 Yaf 的全局注册表来获取在 Bootstrap 中注册的 Memcache 实例,尝试从缓存中获取数据,如果缓存中不存在,则从数据库或其他数据源获取数据,并将其存入缓存中。最后输出数据。 这样,就完成了在 Yaf使用 Memcache 的示例。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

SHUIPING_YANG

你的鼓励是我创作的最大动力。

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值