felipeweb11/laravel-easymutators

为Laravel 5提供值对象变异解决方案。

1.0.12 2018-07-25 12:30 UTC

README

此包提供了一种轻松使用值对象与Eloquent模型的方法。该包中包含了一组默认变异,因此您可以轻松上传图片和/或文件作为值对象并将其保存在Eloquent模型中,您还可以使用我们提供的设置值对象实现来保存或设置数据库中的设置。

以下是一些您可以做的简短示例

$user = User::find(1);
$user->profile_photo = $request->file('photo');

它可以直接处理上传,如上所述,或者直接从URL获取

$user->profile_photo = 'http://www.anyresourceurl.com/some_image.jpg';

稍后您可以这样访问它们

echo $user->profile_photo->url; //Returns photo url
echo $user->profile_photo->width; //Get width of image
echo $user->profile_photo->height; //Get height of image

要求

要创建衍生图像,您的服务器上应安装GD

安装

您可以通过以下命令使用composer安装此包

composer require felipeweb11/laravel-easymutators

接下来,您必须安装服务提供者

// config/app.php
'providers' => [
    ...
    Webeleven\EasyMutators\EasyMutatorsServiceProvider::class,
];

您可以使用以下命令发布配置文件

php artisan vendor:publish --provider="Webeleven\EasyMutators\EasyMutatorsServiceProvider" --tag="config"

这是发布配置文件的内容

return [

    /*
    |--------------------------------------------------------------------------
    | Filesystem Storage Disk
    |--------------------------------------------------------------------------
    |
    | The filesystems on which to store added media. Choose one of the
    | filesystems you configured in app/config/filesystems.php
    |
    */

    'storage_disk' => env('EASYMUTATORS_STORAGE_DISK', 'easymutators'),

    /*
    |--------------------------------------------------------------------------
    | Default image path generator
    |--------------------------------------------------------------------------
    |
    | Default path generator class, used to generate the of files based on
    | mapping.
    |
    */

    'default_path_generator' => \Webeleven\EasyMutators\Upload\DefaultPathGenerator::class,

    /*
    |--------------------------------------------------------------------------
    | Image Driver
    |--------------------------------------------------------------------------
    |
    | This package uses Intervention Image internally that supports "GD Library"
    | and "Imagick" to process images. You may choose one of them according to
    | your PHP configuration. By default PHP's "GD Library" implementation is
    | used.
    |
    | Supported: "gd", "imagick"
    |
    */

    'image_driver' => 'gd',

    /*
    |--------------------------------------------------------------------------
    | Delete old media
    |--------------------------------------------------------------------------
    |
    | Determine if old media should be deleted from filesystem.
    |
    | Options: false, "on-set", "on-save"
    |
    */

    'delete_old_media' => 'on-save',

    /*
   |--------------------------------------------------------------------------
   | Default objects
   |--------------------------------------------------------------------------
   |
   | Default value objects classes, this is an alias array used to map to value
   | object class.
   |
   */

    'objects' => [
        'file' => \Webeleven\EasyMutators\ValueObjects\File::class,
        'image' => \Webeleven\EasyMutators\ValueObjects\Image::class,
        'settings' => \Webeleven\EasyMutators\ValueObjects\Settings::class
    ],

];

最后,您应该在app/config/filesystems.php中添加一个磁盘。这是一个典型的配置

    ...
    'disks' => [
        ...

        'easymutators' => [
            'driver' => 'local',
            'root' => storage_path('app/public/media'),
            'url' => env('APP_URL').'/storage/media',
            'visibility' => 'public',
        ],
    ...

基本用法

以User类为例。首先,您应该在数据库中创建字段。使用迁移,您可以在用户表中创建一个profile_photo字段,用于存储用户的个人资料照片。

class CreateUsersTable extends Migration
{

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            
            $table->increments('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->string('password');
            
            //If you are using MySQL 5.7 you can use JSON column type instead of text
            $table->text('profile_photo')->nullable()->default(null);
            
            $table->rememberToken();
            $table->timestamps();
        });
    }

    ...
}

现在,您应该在模型上使用EasyMutatorsTrait并设置变异字段

...
use Webeleven\EasyMutators\EasyMutatorsTrait;

class User extends Model
{

    use EasyMutatorsTrait;
    
    // Here you should set the attribute name and type.
    // You can use predefined types of easymutators.php config file
    // or create your own value objects that should implements
    // Webeleven\EloquentValueObject\ValueObjectInterface
    protected $mutations = [
        'profile_photo' => 'image'
    ];
    
    // Add field to fillable
    protected $fillable = [
        ...
        'profile_photo',
    ];

}

现在您可以轻松保存图像如下

$user = User::find(1);
$user->profile_photo = $request->file('photo');

//Or directly from an URL
$user->profile_photo = 'http://anyresourceurl/some_image.jpg';

//And save the user in database
$user->save();

处理图像转换

文件的存储由Laravel的文件系统处理,因此您可以使用任何喜欢的文件系统。此外,该包可以为特定图像创建图像转换。如果想要使用,可以在模型上实现mapMedia()方法来配置图像转换,如下所示

...
use Webeleven\EasyMutators\EasyMutatorsTrait;
use Webeleven\EasyMutators\Mapping\MediaMapper;

class User extends Model
{

    use EasyMutatorsTrait;
    
    protected $mutations = [
        'profile_photo' => 'image'
    ];
    
    protected function mapMedia(MediaMapper $mapper)
    {
    
        $profilePhoto = $mapper->image('profile_photo')
                               ->width(900);
    
        $profilePhoto
            ->addConversion('medium')
            ->width(400);
            
        $profilePhoto
            ->addConversion('small')
            ->width(50)
            ->quality(70);
            
        $profilePhoto
            ->addConversion('other')
            ->name('otherFileName')
            ->width(100)
            ->height(50)
            ->generatePathWith('App\MyOwnPathGenerator::class') // Implements Webeleven\EasyMutators\Upload\PathGenerator
            ->dontKeepAspectRatio();
    }

}

稍后您可以这样访问它们

echo $user->profile_photo->medium->url;         //Returns url of medium image
echo $user->profile_photo->medium->width;       //Get width of medium image
echo $user->profile_photo->medium->height;      //Get height of medium image

echo $user->profile_photo->small->url;          //Returns url of small image
echo $user->profile_photo->small->width;        //Get width of small image
echo $user->profile_photo->small->height;       //Get height of small image

//You can also access other attributes like:
echo $user->profile_photo->small->filename;     //Returns filename of image
echo $user->profile_photo->small->name;         //Returns name of image
echo $user->profile_photo->small->path;         //Returns path of image
echo $user->profile_photo->small->size;         //Returns size of image

可选地,您可以设置模型的自定义基础上传目录,默认的基础上传目录是由模型的简短类名 + 实体主键(如果存在)+ 简短哈希组合而成。

...
use Webeleven\EasyMutators\EasyMutatorsTrait;
use Webeleven\EasyMutators\Mapping\MediaMapper;

class User extends Model
{

    use EasyMutatorsTrait;
    
    protected $mutations = [
        'profile_photo' => 'image'
    ];
    
    protected function mapMedia(MediaMapper $mapper)
    {
        ...
        
        //Custom base upload dir for this model
        $mapper->baseUploadDir('nameOfDirectory/' + $this->name);
        
        ...
    }

}

实现自己的值对象

您可以通过实现Webeleven\EloquentValueObject\ValueObjectInterface来创建自己的值对象

interface ValueObjectInterface extends Arrayable
{
    /**
     * @param $value
     */
    public function __construct($value); // Implement logic do construct your value object

    /**
     * @return mixed
     */
    public function toScalar();          // Convert value object to scalar format

    /**
     * @return string
     */
    public function __toString();        // Convert the value objects to database format (string or json string)

    /**
     * @param array $args
     * @return ValueObjectInterface
     */
    public static function make();       // Used to create a new value object instance
}

然后,您可以在模型上配置属性以使用它

...
use Webeleven\EasyMutators\EasyMutatorsTrait;

class User extends Model
{

    use EasyMutatorsTrait;
    
    protected $mutations = [
        'my_attribute' => MyCustomValueObject::class
    ];
    
    // Add field to fillable
    protected $fillable = [
        ...
        'my_attribute',
    ];

}

或者,您可以在easymutators.php配置文件上配置别名

'objects' => [
    ...
    
    'my-custom-value-object' => MyCustomValueObject::class
],

许可证

MIT许可证(MIT)。有关更多信息,请参阅许可证文件