2014-05-25 46 views
1

有什么区别:类的名称作为一个公共函数参数

class PostController extends \BaseController { 
     public function delete($id) { 
     $deletePost = Post::findOrFail($id); 
     return View::make('backend.delete')->with('post', $deletePost); 
     } 
} 

class PostController extends \BaseController { 
     public function delete(Post $post) { 
     return View::make('backend.delete')->with('post', $post); 
     } 
} 

谁能给我解释一下:public function delete(Post $post)

我们采取了一个名为“邮报班“作为变量$post

UPDATE1。

在routes.php文件:

Route::model('post', 'Post'); 

Route::get('delete/{post}', array('uses' => '[email protected]')); 
Route::post('delete', array('uses' => '[email protected]')); 

和PostController.php:

public function delete(Post $post) { 
    return View::make('backend.delete')->with('post', $post); 
} 

public function doDelete() { 
    $post = Post::findOrFail(Input::get('id')); 
    $post->delete(); 

    return Redirect::action('[email protected]'); 
} 

但无论如何,我得到一个错误:没有找到模型[发布]查询结果。 用第二种方法。

+0

不,作为$ post传递的参数必须是'Post'类型的对象实例,或者是扩展'Post' –

+1

http://docs.php.net/manual/en/language.oop5的类的对象实例。 typehinting.php – Deadooshka

回答

2

相当于这只是一个类型提示:

"Type hinting means that whatever you pass must be an instance of (the same type as) the type you're hinting."

在你的榜样它的文章:

public function delete(Post $post) { /* code */ } 

它只是检查$post变量是否实例。所以在你的代码中一切看起来不错。它应该工作。

+0

刚刚清除缓存,它的工作,很奇怪。 – Alex

2

它们都实现了给你模型(如果存在)的同样的事情。

第二种方式称为Route Model binding。路由模型绑定提供了一种将模型实例注入路由的便捷方法。

到模型绑定到一个路线:

Route::model('post', 'Post'); 

接下来,定义一个包含{用户}参数的路由:

Route::get('delete/{post}', array('uses' => [email protected])); 

因此,我们已绑定了{post}参数Post模型,Post实例将被注入到路由中。

这意味着,如果有人达到你的delete()的函数 - 他们已经提供了一个有效的Post模型 - 这是Post::findOrFail($id)

+0

谢谢,我有更新我的问题,请看看 – Alex

相关问题