【问题标题】:Laravel - custom classes don't workLaravel - 自定义类不起作用
【发布时间】:2015-02-07 07:44:14
【问题描述】:

我正在阅读一些关于为 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. Route::get('/' , function() { return Graphics\Image::hello(); } ); 正在返回错误:

使用未定义的常量图形 - 假定为“图形”

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

【问题讨论】:

  • 对于命名空间,您使用反斜杠“\”而不是“/”
  • 然后我得到错误“类图形\图像不存在”
  • 因为你的命名空间,包括类是Graphics\Image\Image。如果你想要Graphics\Image,你需要将你的命名空间更改为Graphics

标签: php laravel classloader composer-php


【解决方案1】:

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

<?php  namespace graphics;

class Image {

    public static function hello() {

    return 'Hello';

    }
}

【讨论】:

  • 如果我使用“命名空间图形\图像;”然后“返回 graphics\Image\Image::hello();”有用。但是如果我使用“命名空间图形;”和“返回图形\图像::你好();”然后它不起作用返回相同的错误。为什么?
【解决方案2】:

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

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

请看这里:What are differences between "php artisan dump-autoload" and "composer dump-autoload"

【讨论】:

    【解决方案3】:

    您不必为自己感到困惑。我正在解决 Laravel 5 中的问题。您不需要将“app/libraries/graphics/Image.php”行添加到composer.json autload 部分,因为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';
         }
    }
    

    现在使用您路线中的图像类。

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

    【讨论】:

      猜你喜欢
      • 2015-05-04
      • 2017-07-20
      • 1970-01-01
      • 2020-05-08
      • 1970-01-01
      • 1970-01-01
      • 2014-09-30
      • 2021-08-02
      • 2020-12-10
      相关资源
      最近更新 更多