CakePHP 3-模型/控制器的全局函数和访问权放在哪里?
我正在使用CakePHP3,有两个问题:CakePHP 3-模型/控制器的全局函数和访问权放在哪里?,php,function,cakephp,model,helper,Php,Function,Cakephp,Model,Helper,我正在使用CakePHP3,有两个问题: 在哪里可以放置全局函数,比如“onlyNumbers()”,只从字符串返回数字。我将在控制器和实体中使用此函数 如何在用户输入的不同DB中插入修改值?让我们举个例子:我有一个输入字段(如邮政编码),js掩码为:xxxxx-xxx,当用户发送它时,cakephp接收带有点和破折号的字符串。我只想在DB中插入数字 我不知道这是否正确,但我认为向实体添加“_setZipCode()”函数并直接修改字符串是可行的,但我如何访问“onlyNumbers()”全
- 在哪里可以放置全局函数,比如“onlyNumbers()”,只从字符串返回数字。我将在控制器和实体中使用此函数
- 如何在用户输入的不同DB中插入修改值?让我们举个例子:我有一个输入字段(如邮政编码),js掩码为:xxxxx-xxx,当用户发送它时,cakephp接收带有点和破折号的字符串。我只想在DB中插入数字李>
namespace App\Controller\Component;
use Cake\Controller\Component;
class GlobalComponent extends Component
{
public function onlyNumbers($string)
{
//Do something to get numbers or what you want
return $result;
}
}
如果希望具有golbal访问权限,请在YourController或AppController中加载组件
class YourController extends Controller
{
public function initialize()
{
parent::initialize();
$this -> loadComponent('Global');
}
public function yourAction()
{
$only_numbers = $this -> Global -> onlyNumbers('ABC123BCA');
}
}
您可以使用“组件” 在src/Controller/Components/GlobalComponent.php中
namespace App\Controller\Component;
use Cake\Controller\Component;
class GlobalComponent extends Component
{
public function onlyNumbers($string)
{
//Do something to get numbers or what you want
return $result;
}
}
如果希望具有golbal访问权限,请在YourController或AppController中加载组件
class YourController extends Controller
{
public function initialize()
{
parent::initialize();
$this -> loadComponent('Global');
}
public function yourAction()
{
$only_numbers = $this -> Global -> onlyNumbers('ABC123BCA');
}
}
您可以将该函数放在应用程序bootstrap.phpIn中。您可以将模型方法添加到
AppModel.php
文件中,然后通过$this->myMethod()
和$this->model->myMethod()在任何模型中访问该文件
同样适用于AppController.php
,但这只能由控制器访问。您可以将该函数放在应用程序bootstrap.phpIn中。您可以将模型方法添加到AppModel.php
文件中,然后可以通过$this->myMethod()在任何模型中访问该文件
和控制器由$this->Model->myMethod()
同样适用于AppController.php
,但这只能由控制器访问。