How to add my own custom class in Laravel 5?

2019-06-16 19:47发布

Ok, in laravel 4, if I want to add my own custom class, eg : library\myFunction.php then I do the following steps :

  1. add "myFunctions.php" into app/library/myFunctiosn.php
  2. at app/start/global.php , within ClassLoader::addDirectories(array( , I add app_path().'/library',
  3. And to call it within my blade view, I add the following codes
<?php
  $FmyFunctions1 = new myFunctions;
  $is_ok1=($FmyFunctions1->is_ok());   
?>
  1. The contents of app/library/myFunctions.php is :
<?php namespace App\library {

    class myFunctions {
        public function is_ok() {
            return 'myFunction is OK';
        }
    }

}
?>

And it works.

But how to do so in Laravel 5 ???

PS : I read What are the best practices and best places for laravel 4 helpers or basic functions?

And tried to add "app/library/", to the autoload array and run composer dum-autoload , but it keeps give me error :

FatalErrorException in xxxx line xx: Class 'myFunctions' not found

I'm also already trying to use :

composer update
composer dump-autoload 
php artisan dump
php artisan clear-compiled
php artisan dump-autoload
php artisan optimize
php artisan route:clear
php artisan route:scan
php artisan route:list 

But still doesn't work...

标签: class laravel
2条回答
趁早两清
2楼-- · 2019-06-16 20:30

This should help you.

FYI: Basically, you could create another directory within app, and then namespace your files in there as appropriate:

app/CustomStuff/CustomDirectory/SomeClass.php.

Then, within your SomeClass.php, make sure you namespace it:

<?php namespace App\CustomStuff\CustomDirectory;

class Someclass {}

Now, you can access this class using the namespace within your classes:

use App\CustomStuff\CustomDirectory\SomeClass;

查看更多
Viruses.
3楼-- · 2019-06-16 20:35

After sometimes for trial and error, I find the answer :

There is no need for modify the composer. Just modify the blade into

<?php
  $FmyFunctions1 = new \App\library\myFunctions;
  $is_ok = ($FmyFunctions1->is_ok());
?>
查看更多
登录 后发表回答