如何在 laravel 5 中解析带有 make 参数的控制器?
How to resolve a controller with make parameter in laravel 5?
以前我可以这样做:
/var/www/laravel/app/Http/Controllers/HelloController.php
<?php namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Models\Hello\Hello as Hello;
class HelloController extends Controller {
public function index() {
$o = new Hello;
$o = new Hello('changed1','changed1');
var_dump($o);
}
}
/var/www/laravel/app/Models/Hello
<?php namespace App\Models\Hello;
use Illuminate\Database\Eloquent\Model\Hello.php;
class Hello extends Model
{
public function __construct($one='default1', $two='default2')
{
echo "First Param: $one","\n<br>\n";
echo "Second Param: $two","\n<br>\n";
echo "\n<br>\n";
}
}
routes.php
Route::get('tutorial', function() {
$app = app();
$app->make('Hello');
});
无需 make 即可实例化,但这会带来错误:
ReflectionException in Container.php line 776: Class Hello does not exist
你认为我在这里缺少什么?
因为您的 class 具有 App\Models\Hello
的 namespace
,您必须在尝试实例化 class 时使用它的 namespace
。因此,你的代码应该是这样的:
Route::get('tutorial', function() {
$app = app();
$app->make('App\Models\Hello\Hello');
});
为了在答案中扩展一点,您可以删除 make()
方法调用并只使用 app()
帮助程序,您最终会得到相同的结果:
Route::get('tutorial', function() {
$app = app();
$app->make('App\Models\Hello\Hello');
// you can achieve the same with the
// `app()` helper using less characters :)
app('App\Models\Hello\Hello');
});
以前我可以这样做:
/var/www/laravel/app/Http/Controllers/HelloController.php
<?php namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Models\Hello\Hello as Hello;
class HelloController extends Controller {
public function index() {
$o = new Hello;
$o = new Hello('changed1','changed1');
var_dump($o);
}
}
/var/www/laravel/app/Models/Hello
<?php namespace App\Models\Hello;
use Illuminate\Database\Eloquent\Model\Hello.php;
class Hello extends Model
{
public function __construct($one='default1', $two='default2')
{
echo "First Param: $one","\n<br>\n";
echo "Second Param: $two","\n<br>\n";
echo "\n<br>\n";
}
}
routes.php
Route::get('tutorial', function() {
$app = app();
$app->make('Hello');
});
无需 make 即可实例化,但这会带来错误:
ReflectionException in Container.php line 776: Class Hello does not exist
你认为我在这里缺少什么?
因为您的 class 具有 App\Models\Hello
的 namespace
,您必须在尝试实例化 class 时使用它的 namespace
。因此,你的代码应该是这样的:
Route::get('tutorial', function() {
$app = app();
$app->make('App\Models\Hello\Hello');
});
为了在答案中扩展一点,您可以删除 make()
方法调用并只使用 app()
帮助程序,您最终会得到相同的结果:
Route::get('tutorial', function() {
$app = app();
$app->make('App\Models\Hello\Hello');
// you can achieve the same with the
// `app()` helper using less characters :)
app('App\Models\Hello\Hello');
});