16

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...

4
  • Try running composer dump-autoload instead Commented Nov 15, 2014 at 6:58
  • already and doesn't work either Commented Nov 15, 2014 at 7:15
  • use namespace autoloading in composer.json Commented Nov 15, 2014 at 9:49
  • already and doesn't work... Commented Nov 15, 2014 at 19:58

2 Answers 2

38

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;
Sign up to request clarification or add additional context in comments.

2 Comments

Filename & Class name should have the same name.
This is right, but you also need to add the folder to composer.json as specified in Amit's answer here stackoverflow.com/questions/41319341/…
10

After some trial and error, I found the answer.

There is no need to modify Composer. Just modify the Blade into:

<?php
  $FmyFunctions1 = new \App\library\myFunctions;
  $is_ok = ($FmyFunctions1->is_ok());
?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.