Where to place menu logic in Laravel?

前端 未结 2 1406
[愿得一人]
[愿得一人] 2021-01-31 22:38

What is best conceptual place to put menu data logic in Laravel. If I use Menu bundle where to put it. In Base_Controller create additional function or something di

相关标签:
2条回答
  • 2021-01-31 23:30

    How about fetching the data in a view composer and using a HTML macro for generating the HTML?

    Laravel often has many ways of doing things. That said, this can probably be a little overwhelming and confusing at times.

    0 讨论(0)
  • 2021-01-31 23:36

    Note: this answer was written for Laravel 3 and might or might not work with the most recent Laravel 4


    My favorite way of creating dynamic menu is achieved by separating the menu part from main layout and injecting the menu data via Laravel's Composer (don't confuse it with Composer PHP package manager, they are different things)

    <!-- layouts/default.blade.php -->
    
    <div id="header">Title</div>
    
    <div id="menu">
        @render('parts.menu')
    </div>
    
    <div id="content"></div>
    <div id="footer"></div>
    

     

    <!-- parts/menu.blade.php -->
    
    <ul>
    @foreach($menuitems as $menuitem)
        <li>{{ $menuitem->title }}</li>
    @endforeach
    </ul>
    

     

    Finally we can inject the variable via composer.

    <?php 
    
    // application/routes.php
    
    View::composer('parts.menu', function($view){
        $view->with('menuitems', Menu::all());
    });
    

    This way everytime parts/menu.blade.php is called, Composer will intercept the view and inject it with $menuitems variable. It's same as using with on return View::make('blahblah')->with( 'menuitems', Menu::all() )

    Hope it helps :)


    Edit: If you don't like to have logics in routes.php you can put it in start.php and consider Jason Lewis' way of splitting the start.php into separate files.

    Create a directory in application called start and fill it with some files.

        + application [DIR]
        \-> + start [DIR]
            |-> autoloading.php
            |-> composers.php
            |-> filters.php
            \-> validation.php
    

    Then add these lines of code into the end of your application/start.php

    require __DIR__ . DS . 'start' . DS . 'autoloading.php';
    require __DIR__ . DS . 'start' . DS . 'filters.php';
    require __DIR__ . DS . 'start' . DS . 'composers.php';
    require __DIR__ . DS . 'start' . DS . 'validation.php';
    

    You got the idea. Put the composer functions in composers.php.

    Read the entire article here: http://jasonlewis.me/article/laravel-keeping-things-organized

    0 讨论(0)
提交回复
热议问题