How can I use my custom class in a view on Laravel

2019-02-14 03:47发布

问题:

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:

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?

Thanks

回答1:

You have two options, make a Service or 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:

<?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:

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

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

Service Provider

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



回答2:

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

Just create a class like:

app/Containers/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!