如何在 Laravel 控制器中包含一些文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21049431/
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 include some file inside a laravel controller
提问by Belmark Caday
I have a file that calculates something, lets say tax. Tax.php
, this is inside some folder, lets say /MyCalculations/Taxes/Tax.php
.
我有一个文件可以计算一些东西,比如说税收。Tax.php
,这是在某个文件夹内,让我们说/MyCalculations/Taxes/Tax.php
。
Now I want this file to be accessible inside my controller, How do I access this file, or how do I access those calculations inside this file?
现在我希望这个文件可以在我的控制器中访问,我如何访问这个文件,或者我如何访问这个文件中的那些计算?
Sample code of Tax.php:
Tax.php的示例代码:
<?php namespace MyCalculations/Taxes;
class Taxes extends Enginge {
//some calculations here
}
?>
I'm using laravel. Thanks
我正在使用 Laravel。谢谢
采纳答案by nielsiano
You could start by creating a namespace for your application, and place a folder in your app directory, perhaps app/Projectname. Then you could place your calculations namespace there there. Then autoload everything in your project by adding
您可以首先为您的应用程序创建一个命名空间,然后在您的应用程序目录中放置一个文件夹,可能是 app/Projectname。然后你可以把你的计算命名空间放在那里。然后通过添加自动加载项目中的所有内容
"autoload": {
"classmap": [
"..."
],
"psr-0": {
"Projectname": "app/"
}
},
to your composer.json file and then do a dump-autoload. Then you could use dependency injection in your controller, like so:
到您的 composer.json 文件,然后执行转储自动加载。然后你可以在你的控制器中使用依赖注入,像这样:
use Projectname\MyCalculations\Taxes\Tax;
class TaxController extends BaseController {
protected $tax;
public function __construct(Tax $tax)
{
$this->tax = $tax;
}
public function getTaxValue()
{
$value = Input::get('value');
return $this->tax->getAwesome($value);
}
回答by Antonio Carlos Ribeiro
Edit your composer.json file and add the 'files' section to it to it:
编辑您的 composer.json 文件并将“文件”部分添加到其中:
"autoload": {
...
"files": [
"app/MyCalculations/Taxes/Tax.php"
]
},
Then you just have to execute:
然后你只需要执行:
composer dump-autoload
And use them everywhere.
并在任何地方使用它们。
If you are on PHP 5.5, you also can use traits:
如果您使用的是 PHP 5.5,您还可以使用特征:
<?php namespace MyCalculations/Taxes;
trait TaxesTraits {
function calculateX()
{
}
}
class Taxes extends Enginge {
use TaxesTraits;
public function calculate()
{
$x = $this->calculateX();
}
}