2011-09-16 29 views
4

我一直在从头开始创建少量的库/类。我来自一个codeigniter背景,我正在尝试制作一些具有类似功能的库。我不断遇到有关对象的问题。组织对象和库

以某种方式创建超级对象$this的最佳方式是?我的主要问题是,我创建了一个视图对象和我运行一个叫load功能看起来像这样:

class View { 

     public function __construct() { 
     } 

     public function load($file = NULL, $data = array()) { 
       if($file) { 
         $file .= '.php'; 
         if(file_exists($file)) { 
           // Extract variables BEFORE including the file 
           extract($data); 
           include $file; 
           return TRUE; 
         } else { 
           echo 'View not found'; 
           return FALSE; 
         } 
       } else { 
         return FALSE; 
       } 
     } 
} 
在我的PHP文件

以后,我就在上面include 'libraries.php';看起来像:

include 'database.php'; 
include 'view.php'; 
include 'input.php'; 
include 'form.php'; 

$config = array(
     'host' => 'localhost', 
     'username' => 'username', 
     'password' => 'password', 
     'database' => 'database' 
); 

$database = new Database($config); 
$view = new View(); 
$input = new Input(); 
$form = new Form(); 

从我包括这些库的文件中,我可以写出类似$form->value('name');这样的文件而没有错误。但是,如果我这样做:

$view->load('folder/index', array('var_name' => 'var_value'));然后从folder/index.php文件我可以访问$var_name就好了,但不是$form->value('name');。我得到的错误,如Call to a member function value() on a non-object in ...

我的问题是如何组织我的图书馆和类的方式将是可重用的。我不想使用前端加载器(一个index.php文件,所有内容都先运行)。这可能是我编写课程的方式的一个问题,但我认为这是一个更大的问题,关于事情的位置等。

+0

使用命名空间(至少假的),并自动加载 – arnaud576875

+0

'我不希望使用前端装载机(的index.php文件,一切都通过第一次运行)'我真的很好奇,为什么? – Alfwed

+3

尽管我不推荐它,但您可以使用注册表访问所有对象。另一种选择是做一些依赖注入。 – Alfwed

回答

1

将您的库/类文件放在一个公共目录中。喜欢的东西:

www 
|_includes 
| |_classes 
| | |_view.php 
| |_config 
| |_database.php 
|_other_folder 
    |_index.php 

然后,您可以设置常用的包含这个在您的.htaccess文件路径“包括”目录:

php_value include_path .:/path/to/www/includes 

然后other_folder/index.php文件只是需要这样的:

​​