将Laravel 5.1注入"Illuminate \ Http \ Request"在您的自定义课程中? [英] Injecting Laravel 5.1 "Illuminate\Http\Request" in your custom classes?
问题描述
这是我简单的 App \ Libraries \ Gelocation.php 类,
namespace App\Libraries;
use Location;
use Illuminate\Http\Request;
class GeoLocation
{
public function getLocationByIP($ip = null)
{
// If IP address is set
if ($ip) {
$location = Location::get($ip);
} else {
$location = Location::get();
}
// Get the location by city
return $location->cityName;
}
public function getLocationByCoordinates($longitute, $latitude)
{
//
}
public function getLocation(Request $request)
{
// Check if the location is already set in the cookie
if ($request->cookie('location')) {
return $request->cookie('location');
} else {
$location = $this->getLocationByIP();
// Set location in the cookie
$request->cookie()->forever('location', $location);
return $location;
}
}
}
我正在如下的 PagesController.php 控制器中使用此类,
I am using this class in my PagesController.php controller as follows,
namespace App\Http\Controllers;
use App\Libraries\GeoLocation;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class PagesController extends Controller
{
public $location;
public function __construct(GeoLocation $location)
{
$this->location = $location;
}
public function index()
{
dd($this->location->getLocation());
return view('pages.index');
}
}
但是,当我运行此代码时,出现此错误,
However, when I run this code I get this error,
GeoLocation.php第28行中的ErrorException:
ErrorException in GeoLocation.php line 28:
传递给App \ Libraries \ GeoLocation :: getLocation()的参数1必须为 Illuminate \ Http \ Request的实例,未给出,在 第22行的/var/www/blogs/app/Http/Controllers/PagesController.php和 定义
Argument 1 passed to App\Libraries\GeoLocation::getLocation() must be an instance of Illuminate\Http\Request, none given, called in /var/www/blogs/app/Http/Controllers/PagesController.php on line 22 and defined
推荐答案
您只需要在Geolocation构造函数中注入Request
,就像这样:
You simply need to inject Request
in Geolocation constructor like so:
namespace App\Libraries;
use Location;
use Illuminate\Http\Request;
class GeoLocation
{
public function __construct(Request $request){
$this->request = $request;
}
public function getLocationByIP($ip = null)
{
// If IP address is set
if ($ip) {
$location = Location::get($ip);
} else {
$location = Location::get();
}
// Get the location by city
return $location->cityName;
}
public function getLocationByCoordinates($longitute, $latitude)
{
//
}
public function getLocation() //no need to inject here
{
// Check if the location is already set in the cookie
if ($this->request->cookie('location')) {
return $request->cookie('location');
} else {
$location = $this->getLocationByIP();
// Set location in the cookie
$request->cookie()->forever('location', $location);
return $location;
}
}
}
这篇关于将Laravel 5.1注入"Illuminate \ Http \ Request"在您的自定义课程中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!