CodeIgniter中getMethod方法已弃用?求原因及修复方案
解决CodeIgniter中Request::getMethod()弃用问题
替代方案
针对getMethod()方法弃用的问题,有两种可行的解决方式:
方式1:直接使用请求类型判断方法(推荐)
CodeIgniter提供了更直观的is()方法来判断请求类型,无需手动比较方法名,彻底规避大小写和弃用问题:
public function insert() { if ($this->request->is('post')) { // 不区分大小写,传入'POST'也可正常判断 $validation = \Config\Services::validation(); $rules = [ "txtSN" => [ "label" => "Student Number", "rules" => "required" ], "txtFN" => [ "label" => "First Name", "rules" => "required|min_length[3]|max_length[20]" ], "txtMN" => [ "label" => "Middle Name", "rules" => "required|min_length[3]|max_length[20]" ], "txtLN" => [ "label" => "Last Name", "rules" => "required|min_length[3]|max_length[20]" ], "cbSex" => [ "label" => "Sex", "rules" => "required" ], "txtDOB" => [ "label" => "Date of Birth", "rules" => "required" ], ]; } }
方式2:手动处理方法名大小写(需严格匹配时用)
按照PSR-7规范,新版本getMethod()默认返回大写方法名(如'POST'、'GET'),如果确实需要获取方法名并做比较,可直接使用默认返回值:
public function insert() { if ($this->request->getMethod() == 'POST') { $validation = \Config\Services::validation(); $rules = [ "txtSN" => [ "label" => "Student Number", "rules" => "required" ], "txtFN" => [ "label" => "First Name", "rules" => "required|min_length[3]|max_length[20]" ], "txtMN" => [ "label" => "Middle Name", "rules" => "required|min_length[3]|max_length[20]" ], "txtLN" => [ "label" => "Last Name", "rules" => "required|min_length[3]|max_length[20]" ], "cbSex" => [ "label" => "Sex", "rules" => "required" ], "txtDOB" => [ "label" => "Date of Birth", "rules" => "required" ], ]; } }
注:若你的CodeIgniter版本中
getMethod()默认返回小写,只需将比较字符串改为'post',或用strtoupper($this->request->getMethod())转换后再比较。
内容的提问来源于stack exchange,提问作者Zekken
相关产品推荐
相关产品推荐

