如何在控制器 Laravel 中导入自定义类?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38837124/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 14:16:50  来源:igfitidea点击:

How import custom class in controller Laravel?

laravellaravel-5.2

提问by Dev

I have created a new directory Libraryin root of Laravel.

Library在 Laravel 的根目录中创建了一个新目录。

Inside I put the file with class:

在里面我把文件放在类中:

class My { // }

class My { // }

So, in controller Laravel I try to get access to this class:

因此,在控制器 Laravel 中,我尝试访问此类:

App\Library\My

But Laravel does not determine this path.

但是 Laravel 并没有确定这条路径。

This is my code:

这是我的代码:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;

use View;

use App\Library\My;

class HomeController extends Controller
{
 //
}

采纳答案by cp50

As above, make sure it is placed in the App directory and make sure it is properly namespaced e.g.

如上,确保它被放置在 App 目录中,并确保它被正确命名,例如

<?php
  $fOne = new \App\library\functions;
  $isOk = ($fOne->isOk());
?>

回答by Zayn Ali

You have to properly namespace your every class.

你必须正确命名你的每个类。

So you can import your class with usekeyword, like so

所以你可以用use关键字导入你的类,就像这样

use App\Library\My;

....

$my = new My();

Or if you've conflicting class name then you can use askeyword to alias the classname while importing

或者,如果您有冲突的类名,那么您可以as在导入时使用关键字为类名设置别名

use App\Library\My as MySecond;

....

$my = new MySecond();

And if you want to directly access your class within the method then you can access it like so.

如果你想在方法中直接访问你的类,那么你可以像这样访问它。

$my = new \App\Library\My();

Note:The leading \means App was declared in the global scope.

注意:领先\意味着 App 是在全局范围内声明的。

回答by Dinh Phong

You should create Libraryfolder inside appfolder

您应该Libraryapp文件夹内创建文件夹

namespace App\Library\My

namespace App\Library\My

appfolder is alrdy used psr-4

app文件夹已被使用 psr-4

In your controller

在您的控制器中

use App\Library\My as My

use App\Library\My as My

It's work for me. Hope this answer is helpful

这对我有用。希望这个回答有帮助