2010-09-13 116 views
12

CodeIgniter是否支持命名空间?PHP中的命名空间CodeIgniter框架

+1

要问的一个更好的问题是为什么你需要它们?我通常使用前缀或后缀“命名空间”代码。例如,$ this-> user_lib或$ this-> user_m意味着你不会与其他任何东西冲突。我真的很想CI支持Controller_Foo但那不是会很快发生: -/ – 2010-09-13 13:11:52

回答

15

命名空间由php支持,而不是框架(codeigniter在您的情况)。如果你使用的命名空间的PHP版本必须> = 5.3.0 笨dosen`t使用命名空间,因为它被写入支持PHP 4

+0

这里找到了一个解决办法:http://porquero.blogspot.com/2012/03/codeigniter-hmvc-namespaces-part-1.html – 2014-07-24 16:21:01

22

如何获取命名空间中笨

实际工作,您可以使命名空间与您的应用程序模型中的相对路径一起工作。这一修改使得负载模型更容易,也可以让你有接口...

添加到您的application/config/config.php文件

spl_autoload_extensions('.php'); // Only Autoload PHP Files 

spl_autoload_register(function($classname){ 

    if(strpos($classname,'\\') !== false){ 
     // Namespaced Classes 
     $classfile = strtolower(str_replace('\\','/',$classname)); 

     if($classname[0] !== '/'){ 
      $classfile = APPPATH.'models/'.$classfile.'.php'; 
     }    
     require($classfile); 
    } else if(strpos($classname,'interface') !== false){ 
     // Interfaces 
     strtolower($classname); 
     require('application/interfaces/'.$classname.'.php'); 
    } 

}); 

例命名空间类的末尾:

<?php 
// File: application/models/foo/bar.php 
namespace foo; 

class Bar extends \CI_Model implements \Awesome_interface { 

    public $foobar; 

    public function __construct() { 
     return parent::__construct(); 
    } 

    public function getFoobar() { 
     return $this->foobar; 
    } 

    public function setFoobar($val) { 
     $this->foobar = $val; 
    } 

} 

实施例中实例化代码某处:

重要注意事项:请勿使用内置CI_Loader(例如:$ this-> load-> model(); )

// This will Autoload Your Namespaced Class 
$example = new foo\Bar(); 

或可替换地在你的PHP类(例如顶部:控制器,其他型号),你可以做到这一点...接口

<?php 
... 
use foo\Bar as FooBar; 

... 

// Then you can just do this 
$example = new FooBar(); 

例子:

<?php 
// File: application/interfaces/awesome_interface.php 
interface Awesome_interface { 

    public function getFoobar(); 

} 
+0

在对'spl_autoload_register'方法类进行了一些更改之后加载没有错误。 Thx – 2014-05-08 19:27:07

+0

不客气。 – 2014-05-12 16:14:56

+0

@TimothyPerez是否有任何其他方式来加载CodeIgniter 3中具有名称空间的库? – sam 2017-01-14 13:21:27

0

你可以看看这个:yidas/codeigniter-psr4-autoload

Th ÈLIB定义app为CI应用程序根,使得在应用程序的每个类可以装载PSR-4名称空间:

\app\libraries\MemberService::auth(); 
\app\helpers\ArrayHelper::indexBy($input); 
\app\widgets\StatWidget::run(); 
class Blog_model extends app\core\BaseModel {} 
class Car_model implements app\contracts\CarInterface {} 

示例代码定义一个类:

<?php 
namespace app\helpers; 
class ArrayHelper 
{ 
    public static function indexBy($input) {} 
} 

https://github.com/yidas/codeigniter-psr4-autoload