Hi all, I’m new to Yii2. Here is my senario: we all know sometimes we should do check the required parameters before the action executing of a controller, for example:
class SiteController
{
public action sayHi()
{
$name = Yii::$app->request->get('name');
if(empty($name)) { // check the required name here
echo "name is required";
}
echo "Hi $name";
}
}
Now I want to implement this functionality by PHP builtin ReflectionMethod like following:
class BaseController : Controller
{
private static $rRequire = '/require:\s*(.*)/';
private static $seperator = ',';
protected $params;
public function beforeAction($action)
{
$className = $action->controller->id;
$method = $action->actionMethod;
$rm = new \ReflectionMethod($className, $method);
$comment = $rm->getDocComment();
if ($comment && preg_match($rRequire, $comment, $rawMatch)) {
$this->params = array_map('trim', explode(self::$seperator, $rawMatch[1]));
$this->checkRequire();
}
}
protected function checkRequire()
{
foreach($this->params as $param) {
if(Yii::$app->request($param)) {
continue;
} else {
echo "`$param` is required";
die;
}
}
}
}
class SiteController : BaseController
{
/**
* require: name
*/
public action sayHi()
{
$name = Yii::$app->request->get('name')
echo "Hi $name";
}
}
or by a general filter inheriting ActionFilter
So my question is: does Yii2 contain kind of filter like this?
if you want any parameters as required, you can declare like this:
class SiteController
{
public action sayHi($name)
{
echo "Hi $name";
}
}
In a higher level, if it is a form submission, you can declare your variables in your model, and set your rules - required is one of the rules - which can be validated.
Maybe in my situation, there is no suitable Model or Form, I want to do this check in one place, so I don’t need to cheek in the business logic repeatly, because maybe there are many method should do this logic. And what if I want to return client a json object friendly?