how to use different namespaces in a controller in laravel 4.1

爷,独闯天下 提交于 2019-12-11 09:45:40

问题


What I want to do is to use different namespaces in a controller. I have a tree scheme like this:

app/
app/controllers/
app/modules/
app/modules/modulename/
app/modules/modulename/controllers/
app/modules/modulename/controllers/modulecontroller.php
app/modules/modulename/models/
app/modules/modulename/models/modulemodel.php

What I want to do is to call a model from a controller in app/controllers/ folder. Therefore I am supposed to add namespace as follows:

    use App\Modules\Facebook\Controllers\Facebook;

The problem is that when I add a namespace and use App::() function at the sametime, I get the following error:

    Class 'App\Modules\Modulename\Controllers\App' not found

I think it is looking the App::() function in module folder. How can I solve this problem?


回答1:


if you use App inside your App\Modules\Facebook\Controllers namespace, it will be interpreted as App\Modules\Facebook\Controllers\Facebook\App class.

since you don't want to have the previous namespace, you use a \ before App like:

\App::()

or put a use statement of top the class like use App;




回答2:


You probably are creating an unusual namspace scheme. It appears you are namespacing every class from your module differently. You should namespace your code within your module only, like so:

// Adding Onur to the namespace prevents any future namespace collisions.
<?php namespace Onur\Facebook;

After creating your namespace you should add all classes that are outside of your namespace that you want to use as followed.

use Eloquent, Input, Validate, Etc;

This prevents you from adding a \ in front of every class instance, making your code hard maintain and prone to errors. It also gives you a good overview on all the classes you are using in the current class.




回答3:


if you say

use App\Modules\Facebook\Controllers\Facebook;

then you are supposed to use Facebook instead of App... Or don´t I understand your problem correctly?

if you say

use App\Modules\Facebook\Controllers\Facebook as FacebookController;

the you can use FacebookController in your file

if you need Access to the root App, you need to to root it using a leading \

\App::make()


来源:https://stackoverflow.com/questions/23512489/how-to-use-different-namespaces-in-a-controller-in-laravel-4-1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!