简体   繁体   中英

Avoid Laravel facade on controller

I'm using Laravel 5.5 and trying to get used to code by psr-2 standard (just started learning). I analyze all my code with Quafoo QA and go step by step fixing the errors and record them.

By using facades i get this error "Avoid using static access to class" . Because of it i'm trying to avoid using them.
On my controller i have this code:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Events\FileLoaded;
use Illuminate\Support\Facades\Input;
use Illuminate\Auth\Middleware\Authenticate;
use PhpOffice\PhpSpreadsheet\Shared\StringHelper;
use \Illuminate\Contracts\View\Factory as ViewFactory;

class LoadDataController extends Controller
{

    public function index()
    {
        $viewfactory = app(ViewFactory::class);
        return $viewfactory->make('LoadData/index');
    }

    //more code
}

Besides the View Facade i also use DB, Input, Validator and Storage Is this the correct way, are there others?

You don't need to avoid Facades - they are a key part of the framework. But if you want to, you can use dependency injection to include the classes you need as arguments in the controller methods:

class LoadDataController extends Controller
{

  public function index(ViewFactory $viewFactory)
  {
    return $viewfactory->make('LoadData/index');
  }

  //more code
}

Or if you need that in all the controller methods:

class LoadDataController extends Controller
{
  private $viewFactory;

  public function __construct(ViewFactory $viewFactory)
  {
    $this->viewFactory = $viewFactory;
  }

  public function index()
  {
    return $this->viewFactory->make('LoadData/index');
  }

  //more code
}

Of course, this doesn't actually change the functionality of the code you've written, it just rearranges it. I wouldn't take the word of the code analyzer you mentioned as something you are doing wrong. These are standard patterns to use in Laravel.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM