我encounterd我班一个小问题:他们根本就没有经过我的自动加载磁带机加载。面向对象PHP自动加载问题
我得到这个消息的错误:
Warning: require(C:\wamp64\www\blog\appAutoloader.php/Table/PostsTable.php): failed to open stream: No such file or directory in C:\wamp64\www\blog\app\Autoloader.php on line 23
Fatal error: require(): Failed opening required 'C:\wamp64\www\blog\appAutoloader.php/Table/PostsTable.php' (include_path='.;C:\php\pear') in C:\wamp64\www\blog\app\Autoloader.php on line 23
工厂类:
use Core\config;
use Core\Database\MysqlDatabase;
class App {
public $title = "My super site";
private $db_instance;
private static $_instance;
public static function getInstance()
{
if (is_null(self::$_instance))
{
self::$_instance = new App();
}
return self::$_instance;
}
public static function load()
{
session_start();
require ROOT . '/app/Autoloader.php';
App\Autoloader::register();
require ROOT .'/core/Autoloader.php';
Core\Autoloader::register();
}
public function getTable($name)
{
$class_name = '\\App\\Table\\' . ucfirst($name) .'Table';
return new $class_name($this->getDb());
}
public function getDb()
{
$config = Config::getInstance(ROOT . '/config/config.php');
if (is_null($this->db_instance)) {
$this->db_instance = new MysqlDatabase($config->get('db_name'), $config->get('db_user'), $config->get('db_pass'), $config->get('db_host'));
}
return $this->db_instance;
}
}
命名空间应用程序自动加载类:
<?php
namespace App;
class Autoloader {
static function register()
{
spl_autoload_register(array(__CLASS__, 'autoload')); // __CLASS__ load the current class
}
static function autoload($class)
{
if (strpos($class, __NAMESPACE__ .'\\') === 0) {
$class = str_replace(__NAMESPACE__ . '\\', '', $class); // _NAMESPACE_ load the current name_space
$class = str_replace('\\', '/', $class);
require __DIR__ . 'Autoloader.php/' . $class . '.php'; // __DIR__ = the parent folder. Here "app"
}
}
}
命名空间的核心自动加载类:
<?php
namespace Core;
class Autoloader {
static function register()
{
spl_autoload_register(array(__CLASS__, 'autoload')); // __CLASS__ load the current class
}
static function autoload($class)
{
if (strpos($class, __NAMESPACE__ .'\\') === 0) {
$class = str_replace(__NAMESPACE__ . '\\', '', $class); // _NAMESPACE_ load the current name_space
$class = str_replace('\\', '/', $class);
require __DIR__ . 'Autoloader.php/' . $class . '.php'; // __DIR__ = the parent folder. Here "app"
}
}
}
空PostTable
namespace App\Table;
use Core\Table\Table;
class PostsTable extends Table
{
}
索引页:
define('ROOT', dirname(__DIR__));
require ROOT . '/app/App.php';
App::load();
$app = App::getInstance();
$posts = $app->getTable('Posts');
var_dump($posts->all());
如何使它工作吗?
你为什么不使用作曲家? – DaAmidza
我同意@Arslan.H--没有理由不使用作曲家,因为你可以永远忘记自动加载问题。如果你决定走自己的路线,我会祝你好运,整理出来。请记住 - 没有必要重新发明轮子。 – Mjh
我不同意,如果你想知道一个轮子是如何工作的,那么你自己创造一个轮子,重新发明任何东西都没有错。 – ArtisticPhoenix