chiiya/laravel-utilities

Laravel项目的常用工具

5.2.0 2024-06-06 09:54 UTC

README

Latest Version on Packagist GitHub Code Style Action Status Total Downloads

Laravel项目的常用类和工具。

安装

您可以通过composer安装此包

composer require chiiya/laravel-utilities

您可以选择通过以下方式发布配置文件

php artisan vendor:publish --tag="utilities-config"

这是已发布的配置文件内容

return [
    /*
    |--------------------------------------------------------------------------
    | Temporary path
    |--------------------------------------------------------------------------
    | Used for downloads and unzipping files.
    */
    'tmp_path' => storage_path('tmp'),
];

使用方法

TimedCommand - 打印命令执行时间

对Laravel的Command的简单扩展,在完成后打印执行时间。

use Chiiya\Common\Commands\TimedCommand;  
  
class SendEmails extends TimedCommand
{
    protected $signature = 'mail:send {user}';
    
    public function handle(DripEmailer $drip)
    {
        $drip->send(User::find($this->argument('user')));
    }  
$ php artisan mail:send 1
> Execution time: 0.1s  
SetsSender - 设置邮件发送者

为邮件发送者设置发送者(返回路径)的特质,例如处理退回。

use Chiiya\Common\Mail\SetsSender;
  
class OrderShipped extends Mailables
{
    use SetsSender;

    public function build(): self
    {
        return $this
            ->subject('Order shipped')
            ->markdown('emails.orders.shipped')
            ->sender('return@example.com');
    }
}
PresentableTrait - Eloquent模型的视图展示器

类似于已不再维护的laracasts/presenter包的视图展示器。在显示数据之前进行一些操作很有用。

use Chiiya\Common\Presenter\Presenter;

/** @extends Presenter<User> */  
class UserPresenter extends Presenter
{
    public function name(): string
    {
        return $this->first_name.' '.$this->last_name;
    }
}
use Chiiya\Common\Presenter\PresentableTrait;
  
class User extends Model
{
    /** @use PresentableTrait<UserPresenter> */
    use PresentableTrait;
    
    protected string $presenter = UserPresenter::class;
}
<h1>Hello, {{ $user->present()->name }}</h1>
AbstractRepository - 仓库模式的基类仓库

用于仓库模式的基类仓库。它为配置的$model提供了getfindindexsearchcountcreateupdatedelete方法。大多数方法接受可选的$filters参数,可用于将applyFilters方法中配置的过滤器应用于查询。

一般建议仅将仓库用作存储复杂查询和/或多个地方反复使用的查询的地方,否则它们可能被视为反模式。但是,对于更复杂的查询,将它们从服务中分离出来可能很有用。仓库还通过使用描述性方法名称来作为查询的自文档方式。这样,开发人员不必解析数据库查询并试图理解它们的目的,当查看您的应用程序逻辑时。


use Chiiya\Common\Repositories\AbstractRepository;

/**
 * @extends AbstractRepository<Post>
 */
class PostRepository extends AbstractRepository
{
    protected string $model = Post::class;

    /**
     * @return Collection<Post>
     */
    public function postsDiscussedYesterday()
    {
        return $this->newQuery()
            ->whereHas('comments', function (Builder $builder) {
                $builder
                    ->where('created_at', '>=', now()->subDay()->startOfDay())
                    ->where('created_at', '<=', now()->subDay()->endOfDay());
            })
            ->get();
    }

    /**
     * @inheritDoc
     */
    protected function applyFilters(Builder $builder, array $parameters): Builder
    {
        if (isset($parameters['title'])) {
            $builder->where('title', '=', $parameters['title']);
        }

        return $builder;
    }
}
// Find by primary key
$post = $repository->get(10);
// Find (first) by filters
$post = $repository->find(['title' => 'Lorem ipsum']);
// List all entities, optionally filtered
$posts = $repository->index();
$posts = $repository->index(['title' => 'Lorem ipsum']);
// Count entities, optionally filtered
$count = $repository->count();
$count = $repository->count(['title' => 'Lorem ipsum']);
// Create new entity
$post = $repository->create(['title' => 'Some title']);
// Update entity
$repository->update($post, ['title' => 'Lorem ipsum']);
// Delete entity
$repository->delete($post);

// Custom methods
$posts = $repository->postsDiscussedYesterday();
CodeService - 生成大量随机代码

用于在内存中高效生成大量随机、唯一代码的服务类,供以后处理。

use Chiiya\Common\Services\CodeService::class;
          
class CouponService {
    public function __construct(
        private CodeService $service,
    ) {}
          
    public function generateCodes()
    {
        // Optional, import previously exported codes so that we don't generate codes that already exist
        $this->service->import(storage_path('app/exports'));
        // Generate specified amount of random codes using the given pattern and character set
        $this->service->generate(
            1_000_000,
            '####-####-####',
            CodeService::SET_NUMBERS_AND_UPPERCASE,
        );
        // Get generated codes for further processing
        $codes = $this->service->getCodes();
        // ... e.g. bulk insert $codes into database
        // Export newly generated codes into (batched) CSV files. Optionally specify the amount of codes per file
        $this->service->export(storage_path('app/exports'));
        $this->service->export(path: storage_path('app/exports'), perFile: 500_000);
    }
}
CsvReader - 读取CSV文件

针对高性能读取CSV文件的对openspout/openspout csv读取器的包装

$reader = resolve(\Chiiya\Common\Services\CsvReader::class);
$reader->open('/path/to/file.csv');
foreach ($reader->rows() as $row) {
    $values = $row->toArray();
}
$reader->close();
CsvWriter - 写入CSV文件

openspout/openspout csv写入器的包装

$writer = resolve(\Chiiya\Common\Services\CsvWriter::class);
$writer->open('/path/to/file.csv');
$writer->write(['Value 1', 'Value 2']);
$writer->close();
ExcelReader - 读取XLS/XLSX文件

openspout/openspout excel读取器的包装,用于高性能读取XLS/XLSX文件

$reader = resolve(\Chiiya\Common\Services\ExcelReader::class);
$reader->open('/path/to/file.xlsx');
foreach ($reader->getSheetIterator() as $sheet) {
    foreach ($sheet->getRowIterator() as $row) {
        $values = $row->toArray();
    }
}
$reader->close();
ExcelWriter - 写入XLX/XLSX文件

openspout/openspout excel写入器的包装

$writer = resolve(\Chiiya\Common\Services\ExcelWriter::class);
$writer->open('/path/to/file.xlsx');
$writer->setCurrentSheetName('Sheet 1');
$writer->addHeaderRow(['Name', 'Email']);
$writer->write(['John Doe', 'john.doe@example.com']);
$writer->addSheet('Sheet 2');
$writer->write(['Value 1', 'Value 2']);
$writer->close();
FileDownloader - 下载远程文件

用于从远程URL下载文件的实用类。

$downloader = resolve(\Chiiya\Common\Services\FileDownloader::class);
$file = $downloader->download('https://example.com/path/to/file.txt');
dump($file->getPath());
$file->delete();
Zipper - 解压.zip文件

用于解压.zip文件的实用类。

$zipper = resolve(\Chiiya\Common\Services\Zipper::class);
$location = $zipper->unzip('/path/to/file.zip');

变更日志

请参阅CHANGELOG以获取有关最近更改的更多信息。

贡献

请参阅CONTRIBUTING以获取详细信息。

许可

MIT许可证(MIT)。请参阅许可证文件获取更多信息。