如何在 Laravel 5 中添加我自己的自定义类?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26942390/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to add my own custom class in Laravel 5?
提问by Galvion
Ok, in laravel 4, if I want to add my own custom class, eg : library\myFunction.php then I do the following steps :
好的,在 laravel 4 中,如果我想添加我自己的自定义类,例如:library\myFunction.php 那么我执行以下步骤:
- add "myFunctions.php" into app/library/myFunctiosn.php
- at app/start/global.php, within ClassLoader::addDirectories(array(, I add app_path().'/library',
- And to call it within my blade view, I add the following codes
- 将“ myFunctions.php”添加到app/library/myFunctiosn.php
- 在app/start/global.php,在ClassLoader::addDirectories(array(,我添加app_path().'/library',
- 并在我的刀片视图中调用它,我添加以下代码
<?php
$FmyFunctions1 = new myFunctions;
$is_ok1=($FmyFunctions1->is_ok());
?>
- The contents of app/library/myFunctions.php is :
- app/library/myFunctions.php 的内容是:
<?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 ???
但是如何在 Laravel 5 中这样做???
PS : I read What are the best practices and best places for laravel 4 helpers or basic functions?
PS:我阅读了laravel 4助手或基本功能的最佳实践和最佳位置是什么?
And tried to add "app/library/",to the autoload arrayand run composer dum-autoload, but it keeps give me error :
并尝试将“app/library/”添加到自动加载数组并运行composer dum-autoload,但它一直给我错误:
FatalErrorException in xxxx line xx: Class 'myFunctions' not found
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...
但是还是不行...
采纳答案by Galvion
After some trial and error, I found the answer.
经过一些试验和错误,我找到了答案。
There is no need to modify Composer. Just modify the Blade into:
无需修改 Composer。只需将 Blade 修改为:
<?php
$FmyFunctions1 = new \App\library\myFunctions;
$is_ok = ($FmyFunctions1->is_ok());
?>
回答by Captain Sparrow
Thisshould 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.
app/CustomStuff/CustomDirectory/SomeClass.php。
Then, within your SomeClass.php, make sure you namespace it:
然后,在你的 SomeClass.php 中,确保你命名它:
<?php
namespace App\CustomStuff\CustomDirectory;
class Someclass {}
Now, you can access this class using the namespace within your classes:
现在,您可以使用类中的命名空间访问此类:
use App\CustomStuff\CustomDirectory\SomeClass;