思考:PHP如何定义全局变量,不需要通过controller传递,就可以在model中直接使用?
经过一番调研之后,找到了解决办法如下:
if (Utility::isIos(Request::get("deviceType")) && $userVip['coinIos'] >= $costCoin) {
$pass = 1;
$consumeType = self::TYPE_CONSUME_COIN;
} else if ($userVip['coinAndroid'] >= $costCoin) {
$pass = 1;
$consumeType = self::TYPE_CONSUME_COIN;
}
<?php
namespace App\Http\Controllers;
use Validator;
class CustomController extends Controller
{
protected $_appVersion = '';
protected $_deviceType = '';
protected $_deviceName = '';
protected $_sysVersion = '';
public function __construct()
{
$this->middleware(function ($request, $next) {
$deviceAgent = $request->header('device-agent');
if (!empty($deviceAgent)) {
$deviceArr = explode("_", $deviceAgent);
if (count($deviceArr) == 4) {
$this->_appVersion = $deviceArr[0];
$this->_deviceType = $deviceArr[1];
$request->merge(["deviceType" => $this->_deviceType]);
$this->_deviceName = $deviceArr[2];
$this->_sysVersion = $deviceArr[3];
}
}
return $next($request);
});
}
}
还有一个疑问:request是怎么传递到model层的?对model层有没有要求?为什么能直接用?
注意:别用错了Request;Laravel内置了很多种Request
use Illuminate\Support\Facades\Request;
Request::get("deviceType")
总结