在Laravel 4中使用名称空间 [英] Using namespaces in Laravel 4

查看:64
本文介绍了在Laravel 4中使用名称空间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Laravel的新手,通常使用PHP名称空间.在决定创建一个名为File的模型之前,我没有遇到任何问题.如何正确命名空间,以便可以使用文件模型类?

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?

文件是app/controllers/FilesController.phpapp/models/File.php.我正在尝试在FilesController.php中创建一个新的File.

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

推荐答案

一旦掌握了命名空间,命名空间就非常容易.

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

以下面的示例为例:

app/models/File.php

namespace App\Models;

class File {

    public function someMethodThatGetsFiles()
    {

    }
}

app/controllers/FileController.php

namespace App\Controllers;

use App\Models\File;

class FileController {

    public function someMethod()
    {

        $file = new File();
    }
}

声明命名空间:

namespace App\Controllers;

请记住,将类放入命名空间以访问任何PHP内置类时,需要从根命名空间调用它们.例如:$stdClass = new stdClass();将变为$stdClass = new \stdClass();(请参见\)

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 \)

导入"其他命名空间:

use App\Models\File;

这允许您随后使用不带名称空间前缀的File类.

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

或者,您也可以致电:

$file = new App\Models\File();

但是最好的做法是将其放在use语句的顶部,这样您就可以查看文件的所有依赖关系,而无需扫描代码.

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.

完成后,您需要他们运行composer dump-autoload来更新Composer的自动加载功能,以考虑到您新添加的类.

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.

请记住,如果要通过URL访问FileController,则需要定义一条路由并指定完整的名称空间,如下所示:

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');

这会将所有GET/file请求定向到控制器的someMethod()

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

命名空间上查看PHP文档,而Nettut是这篇文章

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

这篇关于在Laravel 4中使用名称空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆