如何在Laravel 5的视图中使用自定义类 [英] How can I use my custom class in a view on Laravel 5

查看:204
本文介绍了如何在Laravel 5的视图中使用自定义类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自定义类,必须在视图中使用.但是我该怎么做?

I have a custom class that I have to use inside my view. But how I do this?

在Laravel 4.2中,我只需运行composer.phar dump-autoload并添加start/local.php如下:

In Laravel 4.2, I simply run composer.phar dump-autoload and add in start/local.php as follow:

ClassLoader::addDirectories(array(
    app_path().'/commands',
    app_path().'/controllers',
    app_path().'/models',
    app_path().'/database/seeds',
    app_path().'/helpers/MyClass',
));

最后,在我的视图内,我只使用我的课程:MyClass::myMethod().同样,我如何使用Laravel 5做到这一点?

Finally, inside my view, I just use my class: MyClass::myMethod(). Again, how I do this with Laravel 5?

谢谢

推荐答案

您有两个选择,分别是ServiceService Provider.

You have two options, make a Service or a Service Provider.

此类可以用作其所有方法均为静态的帮助器.例如,在app/Services文件夹中,您可以创建一个新文件夹:

This class could works as a helper having all its methods statics. For example, in app/Services folder you can create a new one:

<?php
namespace Myapp\Services;

class DateHelper{

    public static function niceFormat(){
        return "This is a nice format";
    }

}

然后,在config/app.php处向此类添加别名,如下所示:

Then, add an alias to this class at config/app.php like so:

'DateHelper' => 'Myapp\Services\DateHelper'

现在,在您的应用程序中,您可以调用niceFormat()方法,如\DateFormat::niceFormat();

Now, In your application you can call the niceFormat() method like \DateFormat::niceFormat();

另一方面,您可以创建一个服务提供者,例如 docs 状态并附加一个外观.

In the other hand, you can create a Service Provider like the docs state and attach a Facade.

这篇关于如何在Laravel 5的视图中使用自定义类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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