3xw / cakephp-utils
该包最新版本(4.1.23)没有可用的许可证信息。
CakePHP 工具插件
4.1.23
2023-11-09 08:40 UTC
Requires
- php: >=7.2
- cakephp/cakephp: ^4.0.0
- firebase/php-jwt: ^5.0
Requires (Dev)
- dev-master
- 4.1.23
- 4.1.22
- 4.1.21
- 4.1.20
- 4.1.19
- 4.1.18
- 4.1.17
- 4.1.16
- 4.1.15
- 4.1.14
- 4.1.13
- 4.1.12
- 4.1.11
- 4.1.10
- 4.1.9
- 4.1.8
- 4.1.7
- 4.1.6
- 4.1.5
- 4.1.4
- 4.1.3
- 4.1.2
- 4.1.1
- 4.1.0
- 4.0.0.9
- 4.0.0.8
- 4.0.0.7
- 4.0.0.6
- 4.0.0.5
- 4.0.0.4
- 4.0.0.3
- 4.0.0.2
- 4.0.0.1
- 4.0.0.0
- 3.x-dev
- 3.7.1.10
- 3.7.1.9
- 3.7.1.8
- 3.7.1.7
- 3.7.1.6
- 3.7.1.5
- 3.7.1.4
- 3.7.1.3
- 3.7.1.2
- 3.7.1.1
- 3.7.1.0
- 3.7.0.14
- 3.7.0.13
- 3.7.0.12
- 3.7.0.11
- 3.7.0.10
- 3.7.0.9
- 3.7.0.8
- 3.7.0.7
- 3.7.0.6
- 3.7.0.5
- 3.7.0.4
- 3.7.0.3
- 3.7.0.2
- 3.7.0.1
- 3.7.0.0
- 3.6.0.9
- 3.6.0.8
- 3.6.0.7
- 3.6.0.6
- 3.6.0.5
- 3.6.0.4
- 3.6.0.3
- 3.6.0.2
- 3.6.0.1
- 3.6.0.0
- 3.5.0.12
- 3.5.0.11
- 3.5.0.10
- 3.5.0.9
- 3.5.0.8
- 3.5.0.7
- 3.5.0.6
- 3.5.0.5
- 3.5.0.4
- 3.5.0.3
- 3.5.0.2
- 3.5.0.1
- 3.5.0.0
- 3.4.0.0
- dev-3.next
- dev-next
This package is auto-updated.
Last update: 2024-09-25 12:42:51 UTC
README
此插件充满了实用的功能
安装
您可以使用 composer 将此插件安装到您的 CakePHP 应用程序中。
安装 composer 包的推荐方法是
composer require 3xw/cakephp-utils
在 src/Application.php 中
use Cake\Http\BaseApplication;
...
class Application extends BaseApplication {
...
public function bootstrap()
{
parent::bootstrap();
this->addPlugin('Trois/Utils', ['routes' => true]);
}
..
}
ORM
行为
- Sluggable 行为
- Translate 行为
规则
- IsUniqueTranslationRule
关联
MinMaxAssocationTrait
namespace App\Model\Table
use Trois\Utils\ORM\Traits\MinMaxAssocationTrait;
class SubscriptionsTable extends Table
{
use MinMaxAssocationTrait;
public function initialize(array $config)
{
...
// custom Association
$this->belongsToMinMax('MinPeriodes', [
'type' => 'MIN',
'field' => 'date',
'className' => 'Periodes',
'foreignKey' => 'subscription_id',
'targetForeignKey' => 'periode_id',
'joinTable' => 'subscriptions_periodes',
'joinType' => 'LEFT'
'joinAlias' => 'SP', // extra stuff: define yourself join alias
'joinExtraConditions' => ['SP.was_present' => true] // extra stuff: add conditions on join clause
]);
}
}
// OR
namespace App\Model\Table
use Trois\Utils\ORM\Traits\MinMaxAssocationTrait;
class LessonsTable extends Table
{
use MinMaxAssocationTrait;
public function initialize(array $config)
{
...
// custom Association
$this->hasOneMinMax('MinPeriode', [
'type' => 'MIN',
'field' => 'date',
'className' => 'Periodes',
'foreignKey' => 'lesson_id',
'joinType' => 'LEFT'
]);
}
}
Shell
- MissingTranslations
- Token
MissingTranslations
tu_miss_i18n $model, ...$locales
Token
ut_token username
视图
- LngSwitchCell
安全性
GUARD 组件
此组件允许您检查构造的请求对象并在需要时清理它...
在您的 src/Controller/AppController.php 中添加以下内容
public function initialize()
{
parent::initialize();
...
// Auth
$this->loadComponent('Auth', [...]);
// Guard
$this->loadComponent('Trois/Utils.Guard',[
'autoload_configs' => [
'Guard.requestBody' => 'guard_request_body'
]
]);
...
}
在 config/guard_request_body.php 中
<?php
use Cake\Http\ServerRequest;
return [
'Guard.requestBody' => [
[
'role' => '*',
'prefix' => 'Book',
'controller' => ['Users','Subscriptions'],
'action' => ['register','registerAndBook'],
'method' => ['POST','PUT'],
'rule' => function($user, $role, ServerRequest $request)
{
// magic here... manipulate request here
}
],
]];
CORS 中间件
在您的 src/Application.php 中添加以下内容
use Trois\Utils\Middleware\CorsMiddleware;
...
public function middleware($middlewareQueue)
{
$middlewareQueue
->add(new CorsMiddleware::class)
/* -- OR -- */
->add(new CorsMiddleware([
// thoses are default options
'all' => [
'Access-Control-Allow-Origin' => '*',
'Access-Control-Allow-Credentials' => 'true',
'Access-Control-Expose-Headers' => 'X-Token',
'Access-Control-Max-Age' => '86400'
],
'options' => [
'methods' => 'GET, POST, OPTIONS, PUT, DELETE'
]
]))
...
}
认证工具
配置示例
config/bootsrap.php
Configure::load('auth', 'default');
src/Controller/Appcontroller.php
$this->loadComponent('Auth', Configure::read('Auth.V2'));
config/auth.php
<?php
use Cake\Core\Configure;
return [
'Auth.V2' => [
'loginAction' => false,
'unauthorizedRedirect' => false,
'checkAuthIn' => 'Controller.initialize' ,
// Authenticate
'authenticate' => [
// map role
'all' => ['finder' => 'Auth'],
// Legacy X-API-TOKEN header token
'Trois/Utils.LegacyToken' => [
'key' => Configure::read('Legacy.key'),
'salt' => Configure::read('Legacy.salt')
],
// with Bearer JWT token
'Trois\Utils\Auth\JwtBearerAuthenticate' => [
'duration' => 3600
],
// Basic username + pass
'Trois\Utils\Auth\BasicToJwtBearerAuthenticate' => [
'fields' => ['username' => 'username'],
'passwordHasher' => 'Trois\Utils\Auth\LegacyPasswordHasher',
],
],
// Cache Storage Engine
'storage' => [
'className' => 'Trois\Utils\Auth\Storage\CacheStorage',
'cache' => 'token'
],
// Authorize
'authorize' => [
'CakeDC/Auth.SimpleRbac' => [
'autoload_config' => 'permissions',
],
],
]
];
双因素认证
设置认证
'Trois\Utils\Auth\TwoFactorAuthenticate' => [
'userModel' => 'ExtranetUsers',
'passwordHasher' => 'App\Auth\NoHasher',
'fields' => [
'username' => 'CLIENT_ID',
'password' => 'Password'
],
'transmitter' => [
'class' => '\Trois\Utils\Auth\TwoFactor\EmailCodeTransmitter', // any child of Trois\Utils\Auth\TwoFactor\AbstractCodeTransmitter
'config' => [
'messages' => [
'success' => 'Un email avec un code vous a été envoyé',
'error' => 'L\'application n\'a pas pu vous envoyer de mail. Veuillez essayer à nouveau.'
],
'email' => [
'field' => 'Email',
'profile' => 'default',
'from' => ['info@xxx' => 'Site xxx'],
'subject' => 'Votre code personnel',
'emailFormat' => 'both',
'template' => 'Trois/Utils.default',
'layout' => 'default',
]
]
],
'verifyAction' => [
'prefix' => 'extranet',
'controller' => 'ExtranetUsers',
'action' => 'verify',
'plugin' => false
],
],
缓存
缓存设置
在 config 文件夹中创建一个 cache.php 文件,例如
<?php
return [
'Trois.cache.settings' => [
'default' => 'default', // default cache config to use if not set in rules...
],
'Trois.cache.rules' => [
// cache request
[
'cache' => 'html', // default: 'default', can be a fct($request)
'skip' => false, // default: false, can be a fct($request)
'clear' => false, // default: false, can be a fct($request)
'compress' => true, // default: false, can be a fct($request)
//'key' => 'whatEver',// default is fct($request) => return $request->here()
'method' => ['GET'],
'code' => '200', // must be set or '*' !!!!!
'prefix' => '*',
'plugin' => '*',
'controller' => '*',
'action' => '*',
'extension' => '*'
],
// clear request
[
'cache' => 'html', // default: 'default'
'skip' => false, // default: false
'clear' => true, // default: false,
'key' => '*', // * => Cache::clear(false, cache) (Will clear all keys), 'whatEver' => Cache::delete('whatEver', cache), null => Cache::delete($request->here(), cache)
'method' => ['POST','PUT','DELETE'],
'code' => ['200','201','202'],
'prefix' => '*',
'plugin' => '*',
'controller' => ['Users','Pages'],
'action' => '*',
'extension' => '*'
],
]
];
将缓存作为最后一个中间件
在您的 src/Application.php 文件中添加中间件作为最后一个链式块。这将创建或删除作为缓存(html/json 等)的视图渲染
<?php
namespace App;
...
use Trois\Utils\Middleware\ResponseCacheMiddleware;
class Application extends BaseApplication
{
public function middleware($middleware)
{
$middleware
...
// Apply Response caching
->add(ResponseCacheMiddleware::class);
return $middleware;
}
}
通过 ActionCacheComponent 获取缓存
在 AppController 中加载组件后 Auth!!
$this->loadComponent('Awallef/Cache.ActionCache');
通过 Nginx 获取缓存
首先安装 nginx redis 扩展。然后设置您的缓存配置以存储在 redis 中。您可以使用我的插件...
composer require awallef/cakephp-redis
按如下方式在 app.php 中配置引擎
'Cache' => [
...
'redis' => [
'className' => 'Trois/Utils.Redis',
'prefix' => 'hello.com:',
'duration' => '+24 hours',
'serialize' => true
],
...
]
按如下方式配置 cache.php
return [
'Trois.cache.settings' => [
'default' => 'redis', // default cache config to use if not set in rules...
],
'Trois.cache.rules' => [
// cache request
[
'skip' => false, // default: false, can be a fct($request)
'clear' => false, // default: false, can be a fct($request)
'compress' => true, // default: false, can be a fct($request)
//'key' => 'whatEver',// default is fct($request) => return $request->here()
'method' => ['GET'],
'code' => '200', // must be set or '*' !!!!!
'prefix' => '*',
'plugin' => '*',
'controller' => '*',
'action' => '*',
'extension' => '*'
],
// clear request
[
'clear' => true,
'key' => '*',
'method' => ['POST','PUT','DELETE'],
'code' => ['200','201','202','302'], // 302 is often triggered by cakephp in case of success crud operation...
'prefix' => '*',
'plugin' => '*',
'controller' => '*',
'action' => '*',
'extension' => '*'
],
]
];
也要配置 Nginx
map $http_accept $hello_com_response_header {
default "text/html; charset=UTF-8";
"~*json" "application/json; charset=UTF-8";
}
server {
listen 443;
server_name hello.com;
ssl on;
...
# redis key
set $redis_key "hello.com:$request_uri";
if ($args) {
set $redis_key "hello.com:$request_uri?$args";
}
location / {
redis_pass 127.0.0.1:6379;
error_page 404 405 502 504 = @fallback;
more_set_headers "Content-Type: $hello_com_response_header";
}
#default cake handling
location @fallback {
try_files $uri $uri/ /index.php?$args;
}
location ~ \.php$ {
try_files $uri =404;
include /etc/nginx/fastcgi_params;
fastcgi_intercept_errors on;
fastcgi_pass unix:/var/run/php/php7.1-fpm.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}
}
Redis 缓存
此插件提供了一个与 cakephp 的 RedisEngine 稍有不同的 redis 引擎。不同之处在于
- 引擎配置带有布尔 'serialize' 选项(默认为 true)
- 读写函数使用配置 'serialize' 选项
- 键以使用 : 和 :* redis 技能的方式存储/读取/删除!
按如下方式在 app.php 中配置引擎
'Cache' => [
...
'redis' => [
'className' => 'Trois/Utils.Redis',
'prefix' => 'www.your-site.com:',
'duration' => '+24 hours',
'serialize' => true
],
...
]