php - yaf. use_namespace=1的情况下,controller怎么使用namespace
ringa_lee
ringa_lee 2017-04-10 16:09:55
[PHP讨论组]

请教个问题:
yaf. use_namespace=1的情况下,controller怎么使用namespace?

比如:Index.php的内容

use Yaf\Controller_Abstract;
use Yaf\Dispatcher;
class IndexController extends Controller_Abstract
{
    public function indexAction()
    {
        Dispatcher::getInstance()->disableView(0);
        echo 'Great,It Works!';
    }
}

没法加namespace了,文件名是Index.php

路过的怎么处理的,说说

ringa_lee
ringa_lee

ringa_lee

全部回复(5)
巴扎黑

我也想知道答案。 原本想

<?php
namespace App\Controllers;

class IndexController extends Yaf\Controller_Abstract
{
    function indexAction()
    {
        // do sth.
    }
}

一直报错。去掉namespace App\Controllers就行。不知道怎么办了。

阿神

php.ini 开启

yaf.use_namespace = 1
yaf.use_spl_autoload = 1

定义加载器 可以在公用function中

/** 自动加载器 modules */
function autoload_modules($class){
    $class = str_replace('\\', DIRECTORY_SEPARATOR, $class);
    
    ...

    $file = APPLICATION_PATH . DIRECTORY_SEPARATOR . 'xxxx' . $class . '.php';
    if( file_exists($file) )
        Loader::import($file);
}

然后在 Bootstrap 文件中用 spl_autoload_register 自定义加载器

<?php
use \Yaf\Bootstrap_Abstract;
use \Yaf\Dispatcher;
use \Yaf\Loader;

class Bootstrap extends Bootstrap_Abstract
{
    /**  自动加载器 */
    function _initAutoload(Yaf\Dispatcher $dispatcher)
    {
        Loader::import('xxxx/function.php');
        spl_autoload_register('autoload_modules');
    }
}

不过开启 use_spl_autoload 会影响效率

开启的情况下, Yaf在加载不成功的情况下, 会继续让PHP的自动加载函数加载, 从性能考虑, 除非特殊情况, 否则保持这个选项关闭

use_spl_autoload

阿神

也是一直报错,原来是index里加了 namesapce App\Controllers

迷茫

yaf中的controller,model都是属于根命名空间,无需再去定义,自动引入机制这是写在扩展中的,没必要处理

巴扎黑

个人总觉得在一个文件里写一堆的use ......;不太美观。如果跨项目调用 这个文件,会不会出错呢。

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号