Super Simple Trick For Your BaseController.php

Submitted by gravitano - 3 years ago

I think this is very nice and simple :D You can modify at will you. I think this will save the use of `use` when you make a controller that has a namespace

<?php

class BaseController extends \Controller
{   
    protected $aliases = array(
        'app'            => 'app',
        'artisan'        => 'artisan',
        'auth'           => 'auth',
        'auth_reminder_repository' => 'auth.reminder.repository',
        'blade'          => 'blade.compiler',
        'cache'          => 'cache',
        'cache_store'    => 'cache.store',
        'config'         => 'config',
        'cookie'         => 'cookie',
        'crypt'          => 'encrypter',
        'db'             => 'db',
        'events'         => 'events',
        'files'          => 'files',
        'form'           => 'form',
        'hash'           => 'hash',
        'html'           => 'html',
        'lang'           => 'translator',
        'translator'     => 'translator',
        'log'            => 'log',
        'mailer'         => 'mailer',
        'mail'           => 'mailer',
        'paginator'      => 'paginator',
        'auth_reminder'  => 'auth.reminder',
        'queue'          => 'queue',
        'redirect'       => 'redirect',
        'redis'          => 'redis',
        'request'        => 'request',
        'input'          => 'request',
        'router'         => 'router',
        'session'        => 'session',
        'session_store'  => 'session.store',
        'remote'         => 'remote',
        'url'            => 'url',
        'validator'      => 'validator',
        'view'           => 'view',
    );

    public function __get($key)
    {
        $app = app();
        if(array_key_exists($key, $this->aliases))
        {
            return $app[$this->aliases[$key]];
        }
        return $this->$key;
    }
}

### Example Usage

class HomeController extends BaseController
{
    public function index()
	{
		return $this->view->make('home');
	}	

	public function redirectTo()
	{
		return $this->redirect->to('/');
	}

	public function validate()
	{
		return $this->validator->make($this->request->all(), [])->passes();
	}
}

Ads cover the costs of maintaining Laravel-tricks

comments powered by Disqus

Ads cover the costs of maintaining Laravel-tricks