简体   繁体   中英

Laravel, namespaces and PSR-4

I'm trying to set up PSR-4 within a new Laravel 4 application, but I'm getting some troubles achieving what I want when it comes to build controllers.

Here's what I have now :

namespace MyApp\Controllers\Domain;

class DomainController extends \BaseController {

    public $layout = 'layouts.default';

    public function home() {
        $this->layout->content = \View::make('domain.home');
    }
}

I'm not so fond of using \\View , \\Config , \\Whatever to use Laravel's classes. So I was wondering if I could put a use Illuminate\\View; to be able to use View::make without putting a \\ .

Unfortunately, while doing this, I'm getting the following error : Class 'Illuminate\\View' not found .

Could somebody help with this please ?

Assuming BaseController.php has a namespace of MyApp\\Controllers\\Domain

namespace MyApp\Controllers\Domain;

use View;

class DomainController extends BaseController {

    public $layout = 'layouts.default';

    public function home() {
        $this->layout->content = View::make('domain.home');
    }
}

If BaseController.php has other namespace, ie MyApp\\Controllers

namespace MyApp\Controllers\Domain;

use MyApp\Controllers\BaseController;
use View;

class DomainController extends BaseController {

    public $layout = 'layouts.default';

    public function home() {
        $this->layout->content = View::make('domain.home');
    }
}

If, for instance, you controller needs to use another base class from Laravel, lets say Config .

namespace MyApp\Controllers\Domain;

use MyApp\Controllers\BaseController;
use View;
use Config;

class DomainController extends BaseController {

    public $layout = 'layouts.default';

    public function home() {
        $this->layout->content = View::make('domain.home')->withName(Config::get('site.name'));
    }
}

The problem in your case is that View is not located in Illuminate namespace but in Illuminate\\View namespace, so correct import would be not:

use Illuminate\View; 

but

use Illuminate\View\View;

You can look at http://laravel.com/api/4.2/ to find out which namespace is correct for class you want to use

The use of View::make() takes advantage of the Laravel facades. To properly reference the facade, instead of directly referencing the class that gets resolved out of the iOC container, I would use the following:

use Illuminate\Support\Facades\View;

This will reference the View facade that is being used when calling View::make()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM