仅加载一次自动加载

时间:2017-03-19 09:31:58

标签: php frameworks composer-php autoloader

我使用的是使用composer.json

的autoloader.php
"autoload": {
   "classmap": [

        ],
        "psr-4": {
            "App\\": "app/",
             "App\\Helpers\\": "app/lib/Helpers",
             "App\\Traits\\": "app/Traits",

        }
  }

并且在index.php中我有

<?php
require_once 'vendor/autoload.php';

如果在index.php中使用对象任何类,它的工作正常。现在我的问题是我必须在每个类中加载require_once 'vendor/autoload.php';才能正常工作。有任何方法只能在启动时添加它一次。

例如

<?php
require_once 'vendor/autoload.php';

use App\Controllers\HomeController;

$myclass = new HomeController(); 
$myclass->index();

上面的代码可以使用,因为我使用了require_once'proflier / autoload.php';。我在另一个目录中创建了另一个文件

<?php
namespace App\test;

use App\Controllers\HomeController;

$myclass = new HomeController(); 
$myclass->index();

这里我再次添加需要一次。现在我试图避免包括每次包括autoload.php 感谢

1 个答案:

答案 0 :(得分:0)

您只需在应用程序中包含一次Composer Autoloader。 一个好地方是index.php文件,它作为应用程序的中心入口点。

index.php

<?php
require_once 'vendor/autoload.php';

// handle the $_GET parameters (e.g. `index.php?controller=home&action=index`)
// translate them to your controller object
// then call the controller and action requested
// hardcoded for now:

$controller = new \App\Controllers\HomeController(); 
$controller->index();

HomeController.php

<?php
// this controller is instantiated after `index.php`, 
// 'index.php' loaded the Composer Autoloader already.
// Autoloading is available at this point. 
// There is no need to set it up again.

namespace App\Controllers;

class HomeController
{
    public function index() 
    { 
        echo 'Hello from HomeController->index()';
    }
}