在 Laravel 4 中使用命名空间

2022-01-08 00:00:00 namespaces php laravel laravel-4

我是 Laravel 的新手,通常使用 PHP 命名空间.在我决定制作一个名为 File 的模型之前,我没有遇到任何问题.我将如何正确地进行命名空间以便我可以使用我的 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 AppModels;

class File {

    public function someMethodThatGetsFiles()
    {

    }
}

app/controllers/FileController.php

namespace AppControllers;

use AppModelsFile;

class FileController {

    public function someMethod()
    {

        $file = new File();
    }
}

声明命名空间:

namespace AppControllers;

请记住,一旦您将类放入命名空间以访问任何 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 AppModelsFile;

这允许您随后使用没有命名空间前缀的 File 类.

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

您也可以直接调用:

$file = new AppModelsFile();

但最好将其放在 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()

查看 Namespaces 上的 PHP 文档,Nettut 的文档是这篇文章

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

相关文章