2017-03-19 68 views
0

我使用autoloader.php使用composer.json负载自动加载只有一次

"autoload": { 
    "classmap": [ 

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

     } 
    } 

和我的index.php index.php中使用对象有

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

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

例如

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

use App\Controllers\HomeController; 

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

上面的代码工作,因为我已经使用require_once '供应商/ autoload.php' ;.我在另一个目录中创建了另一个文件

<?php 
namespace App\test; 

use App\Controllers\HomeController; 

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

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

回答

0

你只需要在你的应用程序中包括一次Composer自动加载器。 一个好的地方是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()'; 
    } 
}