Laravel-自定义类不起作用


Laravel - custom classes don't work

我正在阅读一些关于为Laravel创建自定义类的教程。我按照说明进行操作,并完全按照教程所说的进行操作:

  1. 创建新文件夹 laravel/app/libraries/graphics/

  2. 编辑了laravel/app/start/global.php我在其中添加了:

    app_path().'/libraries/graphics',
    
  3. 在laravel/app/libraries/graphics/中创建了名为Image的新文件.php使用以下代码:

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

  5. 使用
  6. Route::get('/' , function() { return Graphics'Image::hello(); } );返回错误:

使用未定义的常量图形 - 假定的"图形"

我还在 composer.json autload 部分添加了"app/libraries/graphics/Image.php"行,这应该是不必要的。为什么我会收到此错误?每个教程都显示了相同的过程,但为什么它不起作用?

你的命名空间不应该只是graphics吗?当前文件将创建graphics'Image'Image 。尝试从命名空间中删除Image

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

您是否尝试过改用artisan dump-autoload

它将清除 Laravel 的所有编译代码。

看这里:"php artisan dump-autoload"和"composer dump-autoload"有什么区别

你不需要为自己感到困惑。我正在解决Laravel 5的问题。您不需要将"app/libraries/graphics/Image.php"行添加到composer.json autload部分,因为默认情况下,应用程序目录在App下命名,并由Composer使用PSR-4自动加载标准自动加载。

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

,现在使用路由中的图像类。

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