Skip to content

Instantly share code, notes, and snippets.

@Garbee
Created August 26, 2016 16:21
Show Gist options
  • Save Garbee/823023f5c72d6551ee44814063c5d103 to your computer and use it in GitHub Desktop.
Save Garbee/823023f5c72d6551ee44814063c5d103 to your computer and use it in GitHub Desktop.
<?php
namespace App\Composers;
use Illuminate\Contracts\View\View;
interface Composer
{
public function compose(View $view);
/**
* Get the view name the composer should be used for.
*
* @return string
*/
public static function appliesTo() : string;
}
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Illuminate\View\Factory;
class Composers extends ServiceProvider
{
/** @var \App\Composers\Composer[] */
private $composers = [
\App\Composers\Pages\Home::class,
\App\Composers\Pages\Vendors\Index::class,
\App\Composers\Pages\Vendor\Show::class,
];
public function register()
{
$this->registerComposers($this->app['view']);
}
private function registerComposers(Factory $view)
{
foreach ($this->composers as $composer) {
$view->composer($composer::appliesTo(), $composer);
}
}
}
<?php
namespace App\Composers\Pages;
use App\Composers\Composer;
use App\Http\Kernel;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Contracts\View\View;
use Illuminate\Contracts\Routing\UrlGenerator;
class Home implements Composer
{
/** @var Guard $guard */
private $guard;
/** @var UrlGenerator $urlGenerator */
private $urlGenerator;
public function __construct(Guard $guard, UrlGenerator $urlGenerator)
{
$this->guard = $guard;
$this->urlGenerator = $urlGenerator;
}
public function compose(View $view)
{
$view
->with('loginUrl', $this->urlGenerator->route('login.show'))
->with('logoutUrl', $this->urlGenerator->route('logout'))
->with('user', $this->guard->user());
}
public static function appliesTo() : string
{
return 'pages.home';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment