Doubt about autoload using Poser

Asked

Viewed 343 times

1

I created a very simple example of using autoload using Composer and PSR-7, but I would like to understand a question, below what I did:

Inside my composer.json, added the following:

"autoload" : {
    "psr-4" : {
        "App\\" : "App/"
    }
}

Inside the directory App, I created a very simple class called Log:

<?php 

namespace App;

class Log {

    public function gravarLog()
    {
        return 'Log gravado com sucesso';
    }
} 

?>

And finally I created a file index.php, to carry out the test, it was like this:

<?php 
require_once 'vendor/autoload.php';
use App\Log;

$log = new App\Log();
echo $log->gravarLog();

It worked right, but I wonder if there is any way to use it in this situation, without the need to always use require_once 'vendor/autoload.php'; so how is it done in Laravel, and how do I do it? Is there a pattern, or a methodology?

2 answers

2

It is not possible any file needs its references, The Standard also performs a require as can be seen in the print below:

Importação Autoload Laravel

2


Actually Laravel and any other PHP framework does this require without you noticing.

They use a concept called Front Controller, where the way PHP works, all your requests go through a single file, in case it is usually the index.php.

In the latest version of Laravel, your file index.php does the require of autoload:

<?php

/**
 * Laravel - A PHP Framework For Web Artisans
 *
 * @package  Laravel
 * @author   Taylor Otwell <[email protected]>
 */
define('LARAVEL_START', microtime(true));

/*
|--------------------------------------------------------------------------
| Register The Auto Loader
|--------------------------------------------------------------------------
|
| Composer provides a convenient, automatically generated class loader for
| our application. We just need to utilize it! We'll simply require it
| into the script here so that we don't have to worry about manual
| loading any of our classes later on. It feels great to relax.
|
*/

require __DIR__.'/../vendor/autoload.php';

Behold here in the code.

Concluding: yes, you need to include the autoload at least once in the main file of your application, in your case index.php. Think it could be worse because you don’t need to implement your script of autoload from scratch or include all files with require one at a time (which at the bottom is what the autoload ago).

Reference:

Browser other questions tagged

You are not signed in. Login or sign up in order to post.