2014-05-25 126 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

相關問題