Yada
Yada

Reputation: 31225

Namespacing and autoloading in Laravel

This might be a simple question but I'm wondering how do I autoload useful classes without declaring use statements on every single file.

<?php namespace App\Http\Controllers;

use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\Input;

class HomeController extends Controller
{
    public function index()
    {
        Input::get('query');
    }
}

If I remove the use Illuminate\Support\Facades\Input; line I will get a class not found error because I'm using the Input class.

Is there a way to autoload useful classes like Input, Response, View like in Laravel 4. What's the point of the Aliases in app.php?

Upvotes: 1

Views: 449

Answers (2)

Marcin Nabiałek
Marcin Nabiałek

Reputation: 111829

You can import input class using both:

use Illuminate\Support\Facades\Input;

or

use Input;

then you can use Input::get('query'); code. That's how PHP namespaces work - you can also look at How to use objects from other namespaces and how to import namespaces in PHP for more details about it.

If you don't use use statement for importing class, you can use \Input::get('query'); or \Illuminate\Support\Facades\Input::get('query');.

Aliases allow you not to use fully qualified classes for example \Illuminate\Support\Facades\Input but shorter form \Input. That's why I showed above 2 versions - the shorter one uses aliases and the longer uses full class path. The same mechanism is both in Laravel 4 and Laravel 5 I believe.

Upvotes: 2

Antonio Carlos Ribeiro
Antonio Carlos Ribeiro

Reputation: 87719

The problem is not really in Laravel, but in PHP. When you namespace a class, it assumes that everything inside that class will be in the same namespace, so you have to tell it that, for a particular class, you need it to use a different namespace.

You can use them by referring to the root namespace, like this:

class HomeController extends Controller
{
    public function index()
    {
        \Input::get('query');
    }
}

Upvotes: 1

Related Questions