如何在 Laravel 5 的视图中使用我的自定义类
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28371697/
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
How can I use my custom class in a view on Laravel 5
提问by Ricardo Giaviti
I have a custom class that I have to use inside my view. But how I do this?
我有一个必须在我的视图中使用的自定义类。但我如何做到这一点?
In Laravel 4.2, I simply run composer.phar dump-autoload
and add in start/local.php
as follow:
在 Laravel 4.2 中,我简单地运行composer.phar dump-autoload
并添加start/local.php
如下:
ClassLoader::addDirectories(array(
app_path().'/commands',
app_path().'/controllers',
app_path().'/models',
app_path().'/database/seeds',
app_path().'/helpers/MyClass',
));
Finally, inside my view, I just use my class: MyClass::myMethod()
. Again, how I do this with Laravel 5?
最后,在我看来,我只使用我的类:MyClass::myMethod()
. 再说一次,我如何用 Laravel 5 做到这一点?
Thanks
谢谢
回答by manix
You have two options, make a Service
or a Service Provider
.
您有两个选择, make aService
或 a Service Provider
。
Service
服务
This class could works as a helper having all its methods statics. For example, in app/Services folder you can create a new one:
这个类可以作为一个助手,拥有它的所有方法静态。例如,在 app/Services 文件夹中,您可以创建一个新文件夹:
<?php
namespace Myapp\Services;
class DateHelper{
public static function niceFormat(){
return "This is a nice format";
}
}
Then, add an alias to this class at config/app.php
like so:
然后,为此类添加别名,config/app.php
如下所示:
'DateHelper' => 'Myapp\Services\DateHelper'
Now, In your application you can call the niceFormat()
method like \DateFormat::niceFormat();
现在,在您的应用程序中,您可以niceFormat()
像这样调用方法\DateFormat::niceFormat();
Service Provider
服务提供者
In the other hand, you can create a Service Provider like the docsstate and attach a Facade.
回答by Sanjay Vamja
I just found that you can add any class instance to a view by simple injection.
我刚刚发现您可以通过简单的注入将任何类实例添加到视图中。
https://laravel.com/docs/5.6/blade#service-injection
https://laravel.com/docs/5.6/blade#service-injection
Just create a class like:
只需创建一个类,如:
app/Containers/Helper.php
应用程序/容器/Helper.php
namespace App\Containers;
class Helper {
function foo() {
return 'bar';
}
}
In blade view file:
在刀片视图文件中:
@inject('helper', 'App\Containers\Helper')
<div>
What's Foo: {{ $helper->foo() }}
</div>
And, that's it! Isn't that so cool!
而且,就是这样!是不是很酷!