请知悉:本文最近一次更新为 7年 前,文中内容可能已经过时。

本节对应书里的The request component。
原文翻译整理如下:

请求(request)组件可能是任何框架中最常用的组件之一。 它处理任何HTTP请求(例如GET,POST或DELETE等等),并且还为$ _SERVER变量提供了几个快捷方式。 大多数时候,我们将使用控制器中的请求组件。 Phalcon文档(https://docs.phalconphp.com/en/latest/reference/mvc.html)是这样描述的:
“控制器在模型和视图之间提供”流“,控制器负责处理来自Web浏览器的传入请求,询问数据的模型,并将数据传递到视图以进行呈现。”
在Phalcon中,所有控制器应该扩展PhalconMvcController 组件,并且要通过HTTP GET访问的公共方法的名称应该具有后缀Action。例如:

<?php
class ArticleController extends PhalconMvcController
{
// Method for rendering the form to create an article
public function createAction()
{
}
// Method for searching articles
public function searchAction()
{
}
// This method will not be accessible via http GET
public function search()
{
}
}

好的。 那么我们如何使用请求组件? 简单! 还记得我们在原理(依赖注入)部分讨论了内置组件吗? 请求组件是其中之一。 我们所需要做的就是得到DI。 这是一个如何获取和使用请求组件的示例:

<?php
class ArticleController extends PhalconMvcController
{
public function searchAction()
{
$request = $this->getDI()->get('request');
// You can also use $request = $this->request; but I don't
// recommend it because $this->request can be easily overwritten
// by mistake and you will spend time to debug ... nothing.
$request->getMethod(); // Check the request method
$request->isAjax(); // Checks if the request is an ajax request
$request->get(); // Gets everything, from the request (GET,POST, DELETE, PUT)
$request->getPost(); // Gets all the data submitted via POST method
$request->getClientAddress(); // Return the client IP
}
}

这些只是构建到请求组件中的一些常见方法。
让我们继续下一个重要组件 – Response(响应)。


如您从本文得到了有价值的信息或帮助,请考虑扫描文末二维码捐赠和鼓励。

尊重他人劳动成果。转载请务必附上原文链接,我将感激不尽。


与《零基础学Phalcon 4 request 组件》相关的博文:


留言

avatar
😀
😀😁😂😅😭🤭😋😘🤔😰😱🤪💪👍👎🤝🌹👌