arodu / utilcake
UtilCake 插件用于 CakePHP 4.x
v0.0.2
2020-11-29 21:12 UTC
Requires
- php: >=7.2
- cakephp/cakephp: ^4.0
Requires (Dev)
- phpunit/phpunit: ^8.0
This package is auto-updated.
Last update: 2024-09-07 22:28:53 UTC
README
CakePHP 插件,包含 CakePHP 4.x 的实用工具集合
安装
您可以使用 composer 将此插件安装到您的 CakePHP 应用程序中。
安装 composer 包的推荐方法是
composer require arodu/utilcake
配置
您可以使用 shell 命令来加载插件
bin/cake plugin load UtilCake
或者,您可以在应用程序的 src/Application.php 文件中手动添加加载语句
public function bootstrap(){ parent::bootstrap(); $this->addPlugin('UtilCake'); }
如何使用
Google reCaptcha V3
在控制器文件中
public function initialize(): void{ parent::initialize(); $this->loadComponent('UtilCake.ReCaptcha', [ 'public_key'=>'RECAPTCHA_PUBLIC_KEY', 'secret_key'=>'RECAPTCHA_SECRET_KEY', ]); } // any action public function action(){ // ... if ($this->request->is('post')) { if($this->ReCaptcha->verify($this->request->getData())){ // when the verification is successful // ... }else{ // when the verification is not successful $this->Flash->error(__('reCaptcha failed, try again')); } } // ... }
在模板 templates/ControllerName/action.php
中
echo $this->Form->create(null, ['id'=>'form-id']); // ... echo $this->Form->end(); $this->ReCaptcha->script('#form-id');
Google 登录
使用 AuthenticationComponent
在登录模板中,例如:/templates/Users/login.php
echo $this->GoogleLogin->link(__('Sign in with Google'), ['class' => 'btn btn-block btn-danger', 'escape' => false] );
在控制器文件中,例如:/Controller/UsersController.php
public function initialize(): void{ parent::initialize(); $this->loadComponent('UtilCake.GoogleLogin', [ 'client_id' => GOOGLE_CLIENT_ID, 'client_secret' => GOOGLE_CLIENT_SECRET, 'redirect_uri' => Router::url([ 'controller' => 'Users', 'action' => 'googleLogin', 'prefix' => false, '_full' => true ]), ]); } //... public function googleLogin() { if (!empty($this->request->getQuery('code'))) { try { $data = $this->GoogleLogin->getAccessToken($this->request->getQuery('code')); $user_profile_info = $this->GoogleLogin->getUserProfileInfo($data['access_token']); $user = $this->Users->find() ->where(['Users.email' => $user_profile_info['email']]) ->first(); if ($user) { $this->Authentication->setIdentity($user); $target = $this->Authentication->getLoginRedirect() ?? '/'; return $this->redirect($target); } $this->Flash->error('Invalid google login'); } catch (\Exception $e) { throw new NotFoundException($e->getMessage()); } } return $this->redirect(['action' => 'login']); }