简体   繁体   中英

create a custom external class in laravel 5.5

I would like to create an external class in Laravel, I want to use this class in my cotroller function.

What is the best way to do that?

thanks

Create a class and define its namespace. For example:

<?php
namespace App\Services;
class MyClass
{
    public function doSomething()
    {
        dd('It\'s working');
    }
}

Run composer du command.

You'll be able to use the class in a controller with:

(new App\Services\MyClass)->doSomething();

Or with IoC :

app('App\Services\MyClass')->doSomething();

If you're using IoC, you'll also be able to inject the class into controller constructor:

use App\Services\MyClass;
protected $myClass;
public function __construct(MyClass $myclass)
{
    $this->myClass = $myClass;
}
public function index()
{
    $this->myClass->doSomething();
}

Used common function any file like controller,models and all blade file valid.

Please try your helpers.php file inner created.

file path like : laravel/app/helpers.php

Code

if (!function_exists('classActivePath')) {

   function classActivePath($path) {
       return Request::is($path) ? ' class="active"' : '';
   }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM