Tomas Turan
Tomas Turan

Reputation: 1255

Laravel - custom classes don't work

I was reading some tutorials on creating custom classes for Laravel. I followed instructions and did exactly what tutorials say:

  1. Created new folder laravel/app/libraries/graphics/

  2. Edited laravel/app/start/global.php where I added:

    app_path().'/libraries/graphics',
    
  3. Created new file in laravel/app/libraries/graphics/ named Image.php with this code:

    <?php  namespace graphics/Image;
    
    class Image {
    
        public static function hello() {
    
        return 'Hello';
    
        }
    }
    
  4. Used composer dump-autload command

  5. Route::get('/' , function() { return Graphics\Image::hello(); } ); is returning error:

Use of undefined constant graphics - assumed 'graphics'

I also added "app/libraries/graphics/Image.php"line into composer.json autload section, which should not be neccessary. Why I am getting this error? Every tutorial shows the same procedure for this, but why it doesn't work?

Upvotes: 2

Views: 461

Answers (3)

Dhaval Tailored
Dhaval Tailored

Reputation: 396

You don't need to confusion for yourself. I'm resolve issue into Laravel 5. You don't need to add "app/libraries/graphics/Image.php"line into composer.json autload section because By default, app directory is namespaced under App and is autoloaded by Composer using the PSR-4 autoloading standard.

<?php 
namespace App\libraries\graphics;
class Image {
     public static function hello() {
         return 'Hello';
     }
}

and now use your Image Class from your route.

Route::get('graphics',function(){
    echo \App\libraries\graphics\Image::hello();
});

Upvotes: 0

Jerodev
Jerodev

Reputation: 33206

Shouldn't your namespace just be graphics? The current file creates graphics\Image\Image. Try removing Image from your namespace.

<?php  namespace graphics;

class Image {

    public static function hello() {

    return 'Hello';

    }
}

Upvotes: 1

iamyojimbo
iamyojimbo

Reputation: 4719

Have you tried using artisan dump-autoload instead?

It will clear all of Laravel's compiled code.

See here: What are differences between "php artisan dump-autoload" and "composer dump-autoload"

Upvotes: 0

Related Questions