Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
165 views
in Technique[技术] by (71.8m points)

php - Using namespaces in Laravel 4

I'm new to Laravel and using PHP namespaces in general. I didn't run into any problems until I decided to make a model named File. How would I go about namespacing correctly so I can use my File model class?

The files are app/controllers/FilesController.php and app/models/File.php. I am trying to make a new File in FilesController.php.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Namespacing is pretty easy once you get that hang of it.

Take the following example:

app/models/File.php

namespace AppModels;

class File {

    public function someMethodThatGetsFiles()
    {

    }
}

app/controllers/FileController.php

namespace AppControllers;

use AppModelsFile;

class FileController {

    public function someMethod()
    {

        $file = new File();
    }
}

Declare the Namespace:

namespace AppControllers;

Remember, once you've put a class in a Namespace to access any of PHP's built in classes you need to call them from the Root Namespace. e.g: $stdClass = new stdClass(); will become $stdClass = new stdClass(); (see the )

"Import" other Namespaces:

use AppModelsFile;

This Allows you to then use the File class without the Namespace prefix.

Alternatively you can just call:

$file = new AppModelsFile();

But it's best practice to put it at the top in a use statement as you can then see all the file's dependencies without having to scan the code.

Once that's done you need to them run composer dump-autoload to update Composer's autoload function to take into account your newly added Classes.

Remember, if you want to access the FileController via a URL then you'll need to define a route and specify the full namespace like so:

Route::get('file', 'App\Controllers\FileController@someMethod');

Which will direct all GET /file requests to the controller's someMethod()

Take a look at the PHP documentation on Namespaces and Nettut's is always a good resource with this article


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...