【问题标题】:How to add my own custom class in Laravel 5?如何在 Laravel 5 中添加我自己的自定义类?
【发布时间】:2015-01-12 13:49:57
【问题描述】:

好的,在 laravel 4 中,如果我想添加自己的自定义类,例如:library\myFunction.php,那么我执行以下步骤:

  1. 将“myFunctions.php”添加到 app/library/myFunctionosn.php
  2. app/start/global.php 中,在 ClassLoader::addDirectories(array() 中,我添加 app_path().'/library',
  3. 为了在我的刀片视图中调用它,我添加了以下代码
<?php
  $FmyFunctions1 = new myFunctions;
  $is_ok1=($FmyFunctions1->is_ok());   
?>
  1. app/library/myFunctions.php 的内容是:
<?php namespace App\library {

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

}
?>

而且它有效。

但是如何在 Laravel 5 中这样做???

PS : 我看了What are the best practices and best places for laravel 4 helpers or basic functions?

并尝试将 "app/library/", 添加到 自动加载数组 并运行 composer dum-autoload ,但它一直给我错误:

在 xxxx 行 xx 中出现 FatalErrorException:找不到类“myFunctions”

我也已经在尝试使用了:

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 

但是还是不行……

【问题讨论】:

  • 尝试运行 composer dump-autoload
  • 已经用了,也不能用
  • 在 composer.json 中使用命名空间自动加载
  • 已经用了,但不起作用...
  • 更新了我的问题

标签: class laravel


【解决方案1】:

经过反复试验,我找到了答案。

无需修改 Composer。只需将 Blade 修改为:

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

【讨论】:

    【解决方案2】:

    This 应该可以帮到你。

    仅供参考: 基本上,您可以在应用程序中创建另一个目录,然后根据需要在其中命名您的文件:

    app/CustomStuff/CustomDirectory/SomeClass.php.

    然后,在您的 SomeClass.php 中,确保为它命名:

    <?php 
    namespace App\CustomStuff\CustomDirectory;
    
    class Someclass {}
    

    现在,您可以使用类中的命名空间访问该类:

    use App\CustomStuff\CustomDirectory\SomeClass;
    

    【讨论】:

    猜你喜欢
    • 2016-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-14
    • 2022-01-09
    • 2016-02-18
    • 1970-01-01
    相关资源
    最近更新 更多