A
A
Andrey Sokolov2014-08-12 21:37:35
Laravel
Andrey Sokolov, 2014-08-12 21:37:35

Laravel: Template stubs?

Hello, I ran into a problem about not really knowing how to make repetitive code in Laravel.
Let's say I have 2 Controllers:
BaseController
HomeController
Let's say in both I need to pass layout.main -> {{ title }} to the template with the same content
. The most appropriate solution for me is: pass the title using with.
but what if I have 5000 controllers? Is it possible to somehow duplicate the "Template blanks"

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
Ivan Brezhnev, 2014-08-13
@eX1stenZ

You can create a service provider

<?php

use Illuminate\Support\ServiceProvider;

class MyServiceProvider extends ServiceProvider
{
    public function boot()
    {
        //
    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        // Вешаем на роуты
        Route::when('*' , function ()
        {
            View::share('title', 'Дефолтный заголовок');
        });

        // или вот так на определенный шаблон
        View::composer(['layout.main', 'layout.page', /* ... */] , function ($view)
        {
            $view->with('title', 'Дефолтный заголовок');
        });
    }
}

Register this service provider in /app/config/app.php -> providers -> MyServiceProvider
'providers' => [
    /* ... */
    'MyServiceProvider',
    /* ... */
],

You can add providers in a separate folder (for example, app/services), then add it to composer.json
"autoload": {
    "classmap": [
        "app/services"
    ]
}

or is it best to have a separate Namespace for your code

S
Sergey, 2014-08-12
Protko @Fesor

Everything is possible. But 5000 controllers... are you sure what you're doing? You can also use HMVC to solve this problem. In general, if you have a really big project, you should reconsider the choice of framework and take something more suitable, for example Symfony2

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question