假设我们有一个Controllers'Cart
,它有一个方法postAdd()
。当您向 http://www.site.com/cart/add
发送 POST 请求时,将调用此方法。这是将产品添加到购物车的控制器方法,因此显然将发布productId
。
因为我在控制器中执行此操作时所有 POST 数据都将以字符串形式出现
public function postAdd() {
$productId = $this->request->post('productId'); // It is of a 'string' type.
// You would then probably do something like...
$this->shoppingService->addToCart($productId);
.........
}
Services'Shopping
的接口将是
interface ShoppingInterface {
/**
* @param int $productId
* @return bool
*/
public function addToCart($productId);
}
由于 PHP 是松散类型的,我可以将字符串传递给该方法,但数据是否应该首先转换为整数?
你没有某种"Form"类来实现任何类型的验证任务吗?应验证由于不确定性质而导致的任何传入外部数据。您的示例可以像这样重写:
public function postAdd()
{
$form = $this->getProductForm()
->import($this->request->post())
->checkRules();
if ($form->getErrors()) {
return new FormErrorResponse($form);
}
$this->shoppingService->addToCart($form->getValue('productId'));
...
}
当然,表单验证可以提取到私有方法(即checkLoginForm)。我认为没有理由将如此小且易于阅读的行专用于另一个类