In Laravel, which file is indicated to use Macrotraits?

Asked

Viewed 75 times

2

In Laravel, some classes use the trait MacroableTrait.

Through this trait it is possible to create definitions such as:

HTML::macro('urlQuery', function ()
{
     // Faça alguma coisa aqui
});

HTML::urlQuery(); // O método urlQuery é "criado" magicamente

However, I want to make such a definition in a global way.

In which Laravel’s purchase I could make such definitions (keeping as much as possible the organization of the code)?

bootstrap/start.php ?

app/start/global.php ?

Or another file ?

1 answer

3


In bootstrap/start.php I think it’s a bad idea, this file is used to load the autoload and start the Laravel classes themselves.

In the app/start/global.php would also work, but you would lose some of the organization. (It is worth remembering that the app/start/global.php no longer exists in Laravel 5).

I would create a separate file inside my folder app, something like macros.php and would carry it by Composer.json:

"autoload": {
    "classmap": [
        "app/commands",
        "app/controllers",
        "app/models",
        "app/database/migrations",
        "app/database/seeds",
        "app/tests/TestCase.php"
    ],
    "files": [
        "app/macros.php"
    ]
},

Another way would be to define a Service Provider to create all these macros. A own documentation puts an example involving the method macro in the method boot of a Service Provider:

use Illuminate\Contracts\Routing\ResponseFactory;

public function boot(ResponseFactory $factory)
{
    $factory->macro('caps', function ($value) {
        //
    });
}

These are some suggestions. There are several places this can be done and Laravel allows a flexible architecture for your application. So choose what you make the most sense for your project.

  • Bonus can only be granted in 22 hours :\

  • Or else, you could do app/macros/request.php, app/macros/html.php and so on :)

Browser other questions tagged

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