Laravel:如何发起全球图书馆

时间:2018-04-09 03:03:13

标签: php laravel

我有 应用程序/库/ Cart.php
应用程序/库/ Currency.php
应用程序/库/ SomeOther1.php
应用程序/库/ SomeOther2.php
...

在我的所有控制器中,我不想“使用”并声明 我不想要这个:

<?php
namespace App\PathToFolder;

use App\Libraries\Cart;
use App\Libraries\Currency;

class SomeController extends Controller
{
  public someFunction()
  {
    $this->cart = new Cart;
    $this->cart->add(...);
    $this->cart->remove(...);
    $this->cart->clear(...);

    $this->currency = new Currency;
    $this->currency->format(...);
  }

我想要这个

<?php
namespace App\PathToFolder;

class SomeController extends Controller
{
  public someFunction()
  {
    $this->cart->add(...);
    $this->cart->remove(...);
    $this->cart->clear(...);
    $this->currency->format(...);
  }

没有“使用”和“新”的行。怎么做? 服务提供者?中间件?

这也是可以接受的:

$this->library->cart->add(...);  
$this->library->cart->remove(...);  
$this->library->cart->clear(...);  
$this->library->currency->format(...);  

3 个答案:

答案 0 :(得分:1)

您可以在不使用use的情况下尝试以下代码。实际上在实例化中添加命名空间。

<?php
namespace App\PathToFolder;

class SomeController extends Controller
{
  public someFunction()
  {
    $this->cart = new \App\Libraries\Cart;
    $this->cart->add(...);
    $this->cart->remove(...);
    $this->cart->clear(...);

    $this->currency = new \App\Libraries\Currency;
    $this->currency->format(...);
  }

答案 1 :(得分:0)

通常我会做辅助类,你不需要在你的控制器或基本控制器中加载你的大量初始化函数

我创建了新的文件夹调用助手并创建了新的类名helpers.php

在composer.json中的autoload下,在其中添加你的助手类..

"autoload": {
    ...
    "files": ["app/Helpers/helpers.php"]
},

运行composer dumpautoload

并在helper.php类中..参见下面的示例

if (! function_exists('get_cart')) {

    function get_cart()
    {
       return new Cart();
    }
}

用法:

get_cart()->add(...);
get_cart()->remove(...);

如果你不想使用帮助类。只做静态类

用法:

Cart::add(...)
Cart::remove(...)

使用 Trait ,但您仍在$this

中使用 $this->cart->add

答案 2 :(得分:0)

除了其他人提到的使用traits或composer文件之外,还有另外一种方法可以实现此目的。

您可以在父控制器中声明并初始化varible并使用它。

例如,

您的父控制器根据您的代码

<?php

 namespace App\Http\Controllers;

 use Illuminate\Foundation\Bus\DispatchesJobs;
 use Illuminate\Routing\Controller as BaseController;
 use Illuminate\Foundation\Validation\ValidatesRequests;
 use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
 use App\Libraries\Cart;
 use App\Libraries\Currency;

 class Controller extends BaseController
 {
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
    private $cart;
    private $currency;

    public function __construct()
    {
        //blockio init
        $this->cart = new Cart;
        $this->currency = new Currency; 
    }

 }

现在,您可以在控制器中使用此功能

<?php
namespace App\PathToFolder;

class SomeController extends Controller
{
  public someFunction()
  {
    $this->cart->add(...);
    $this->cart->remove(...);
    $this->cart->clear(...);
    $this->currency->format(...);
  }