xepozz/shortcut

一组针对 Yii 框架的快捷方式

This package is auto-updated.

Last update: 2024-08-29 15:24:12 UTC


README

为快速开发 Yii 3 应用程序提供一组辅助函数。

Latest Stable Version Total Downloads phpunit codecov type-coverage

关于

该库提供了一组辅助函数,用于快速开发 Yii 3 应用程序。

安装

composer req xepozz/shortcut

快捷方式

目录

函数

container(string $id, bool $optional = false): mixed

  • $id 是容器 ID
  • $optional 是一个标志,如果 $id 在容器中未找到,则返回 null
container(\App\MyService::class); // => \App\MyService instance
container('not-exist'); // => throws \Psr\Container\NotFoundExceptionInterface
container('not-exist', true); // => null

route(string $name, array $params = [], array $query = []): string

  • $name 是路由名称
  • $params 是路由参数
  • $query 是查询参数
route('site/index'); // => '/index'
route('user/view', ['id' => 1]); // => '/user/1'
route('site/index', [], ['page' => 2]); // => '/index?page=2'

view(string $view, array $params = [], null|string|object $controller = null): \Yiisoft\DataResponse\DataResponse

  • $view 是视图名称
  • $params 是视图参数
  • $controller 是控制器实例或视图目录的路径。用于将视图绑定到特定目录。
view('site/index'); // => A response object with content of file '/views/site/index.php'
view('site/index', ['page' => 2]); // => A response object with content of file '/views/site/index.php' and params ['page' => 2]
view('index', ['page' => 2], new MyController()); // => A response object with content of file '/views/my/index.php' and params ['page' => 2]
view('index', ['user' => $user], 'module/user'); // => A response object with content of file '/views/module/user/index.php' and params ['user' => $user]

class SiteController 
{
    public function actionIndex()
    {
        return view('index', [], $this);  // => A response object with content of file '/views/site/index.php'
    }
}

response(int|null|string|array|StreamInterface $body = null, int $code = 200, string $status = 'OK', array $headers = []): \Psr\Http\Message\ResponseInterface

  • $body 是响应体
  • $code 是响应码
  • $status 是响应状态
  • $headers 是响应头
response('Hello world'); // => A response object with body 'Hello world'
response('Hello world', 201); // => A response object with body 'Hello world' and code 201
response('Hello world', 201, 'Created'); // => A response object with body 'Hello world', code 201 and status 'Created'
response('Hello world', 201, 'Created', ['X-My-Header' => 'My value']); // => A response object with body 'Hello world', code 201, status 'Created' and header 'X-My-Header' with value 'My value'

response(['message' => 'Hello world']); // => A response object with body '{"message":"Hello world"}' and header 'Content-Type' with value 'application/json'

redirect(string $name, array $parameters = [], array $query = [], int $code = Status::TEMPORARY_REDIRECT, bool $absolute = false): \Psr\Http\Message\ResponseInterface

  • $name 是路由名称或绝对 URL(如果 $absolutetrue
  • $parameters 是路由参数。仅当 $absolutefalse 时使用。
  • $query 是查询参数
  • $code 是响应码
  • $absolute 是一个标志,用于生成绝对 URL,默认为 false
// Route name 'site/index' is bound to '/index'
redirect('site/index'); // => A response object with code 307 and header 'Location' with value '/index'
redirect('site/index', ['page' => 2]); // => A response object with code 307 and header 'Location' with value '/index/2'
redirect('site/index', [], ['page' => 2]); // => A response object with code 307 and header 'Location' with value '/index?page=2'
redirect('site/index', [], ['page' => 2], Status::PERMANENT_REDIRECT); // => A response object with code 308 and header 'Location' with value '/index?page=2'

// Generating absolute url
redirect('/path/to/redirect', [], ['page' => 2], Status::PERMANENT_REDIRECT, true); // => A response object with code 308 and header 'Location' with value 'http://localhost/path/to/redirect?page=2'

alias(string $path): string

  • $path 是别名名称
alias('@runtime'); // => '/path/to/runtime'

aliases(string ...$paths): array

  • $paths 是别名名称
aliases('@runtime', '@webroot'); // => ['/path/to/runtime', '/path/to/webroot']

translate(string $message, array $params = [], string $category = 'app', string $language = null): string

  • $message 是翻译消息
  • $params 是翻译参数
  • $category 是翻译类别
  • $language 是翻译语言
translate('main.hello'); // => 'Hello world'
translate('error.message', ['message' => 'Something went wrong']); // => 'Error: "Something went wrong".'
translate('error.message', ['message' => 'Something went wrong'], 'modules'); // => 'Error from a module: "Something went wrong".'
translate('error.message', ['message' => 'Something went wrong'], 'modules', 'ru'); // => 'Ошибка из модуля: "Something went wrong".'

validate(mixed $data, callable|iterable|object|string|null $rules = null, ?ValidationContext $context = null): Result

  • $data 是要验证的数据
  • $rules 是验证规则
  • $context 是验证上下文
validate(
    ['name' => 'John'],
    ['name' => [new Required()]],
);

有关验证规则的更多信息,请参阅 yiisoft/validator

log_message(string $level, string|stringable $message, array $context = []): void

  • $level 是一个日志级别。支持的级别:emergencyalertcriticalerrorwarningnoticeinfodebug
    • 您可以使用 \Psr\Log\LogLevel 常量
      • \Psr\Log\LogLevel::EMERGENCY
      • \Psr\Log\LogLevel::ALERT
      • \Psr\Log\LogLevel::CRITICAL
      • \Psr\Log\LogLevel::ERROR
      • \Psr\Log\LogLevel::WARNING
      • \Psr\Log\LogLevel::NOTICE
      • \Psr\Log\LogLevel::INFO
      • \Psr\Log\LogLevel::DEBUG.
  • $message 是一个日志消息
  • $context 是一个日志上下文

此外,您还可以使用特定级别的函数

  • log_emergency(string|Stringable $message, array $context = []): void
  • log_alert(string|Stringable $message, array $context = []): void
  • log_critical(string|Stringable $message, array $context = []): void
  • log_error(string|Stringable $message, array $context = []): void
  • log_warning(string|Stringable $message, array $context = []): void
  • log_notice(string|Stringable $message, array $context = []): void
  • log_info(string|Stringable $message, array $context = []): void
  • log_debug(string|Stringable $message, array $context = []): void
log_message('info', 'Some info message');
log_message('error', 'Could not authenticate user with ID {user_id}', ['user_id' => $userId]);

log_info('Info message');
log_error('Error message');
log_warning('Warning message');
log_notice('Notice message');
log_debug('Debug message');
log_critical('Critical message');
log_alert('Alert message');
log_emergency('Emergency message');

cache(string|int|Stringable|array $key, mixed $value = null, int|DateInterval|null $ttl = null): mixed

  • $key 是一个缓存键
  • $value 是一个缓存值
  • $ttl 是一个缓存的有效期
cache('key', 'value'); // returns "value" and sets cache with key "key" if it does not exist

cache('key', 'value', 3600); // sets cache with key "key" and value "value" for 1 hour
cache('key', 'value', new DateInterval('PT1H')); // also TTL can be an instance of DateInterval

cache('key', fn () => 'value'); // $value can be a closure. It will be executed only if cache with key "key" does not exist

cache(new StringableClass('key'), fn () => 'value'); // $key can be an instance of Stringable
cache(12345, fn () => 'value'); // $key can be an integer
cache(['key' => 'value', '!@#$%^&*()_+`' => '_)(*&^%$#@!~`'], fn () => 'value'); // $key can be an array. It will be serialized to a JSON and the following characters will be replaced to "_": {}()/\@:

寻找更多模块?

  • Unique ID - 允许您跟踪应用中的唯一用户。
  • Request ID - 一个用于生成唯一请求和响应ID的简单库,用于跟踪目的。
  • AB - 一个简单的库,可以基于一组规则启用A/B测试。
  • Feature Flag - 一个简单的库,可以基于一组规则启用/禁用功能。