Controller中的代码行重复,用它们创建方法的位置


Lines of code duplicated in Controller, where to create a method with them?

Aloha,我的控制器中有两个方法,一个用于设置配置文件图片,另一个用于更新它。我在两种方法中都使用这行代码:

    $user = Auth::user();
    if (Input::file('image')) {
        $image = Image::make(Input::file('image'));
        $fullName = Input::file('image')->getClientOriginalName();
        $extension = Input::file('image')->getClientOriginalExtension();
        $pathToCreate = public_path() .'/images/'. $user->email . '/';
        $fullPath = $pathToCreate . $user->email . '.' . $extension;
        $pathDatabase = 'images/' . $user->email . '/' . $user->email . '.' .$extension;
        // Creating directory if it does not exists
        File::exists($pathToCreate) or File::makeDirectory($pathToCreate);
        $image->resize(null, 145, function ($constraint) { $constraint->aspectRatio(); })
            ->crop(130,130)
            ->save($fullPath);
        $user->picture = $pathDatabase;

我想用这几行代码创建一个方法,但我觉得控制器不是一个好地方。我应该把这个方法放在哪里?

一般来说,这取决于代码的用途。如果这是您网站上唯一使用该代码的地方,那么在Controller类中包含该代码作为私有方法是完全可以接受的。

如果此代码将在其他控制器中使用,则可能需要创建一个服务类来处理此问题。当在控制器中使用时,这相当于以下内容:

$user->picture = $this->fileUploadService->process( Input::file('image') );

最简短的答案是:把它放在最有意义的地方。通用解决方案应作为一项服务广泛提供。特定的解决方案应该放在需要特定性的地方(控制器、存储库、模型等)

您应该查看Laravel Stapler。对于处理Laravel中的图像上传非常有用。https://github.com/CodeSleeve/laravel-stapler

您可以将图像附加(或"装订")到模型上,而不是保存图像并检查其是否存在。

下面是从文档中获取的关于如何设置表单的示例。

 <?= Form::open(['url' => action('UsersController@store'), 'method' => 'POST', 'files' => true]) ?>
    <?= Form::input('first_name') ?>
    <?= Form::input('last_name') ?>
    <?= Form::file('picture') ?>
    <?= Form::submit('save') ?>
 <?= Form::close() ?>

该模型的控制器中会有这样的东西:

 $this->hasAttachedFile('picture', [
        'styles' => [
            'thumbnail' => '100x100',
            'large' => '300x300',
            'pictureCropped' => '75x75#'
        ],
        'url' => '/system/:attachment/:id_partition/:style/:filename',
        'default_url' => '/:attachment/:style/missing.jpg'
    ]);

那么你在控制器中所做的就是User::create(Input::all());

检查"附件"的存在与if ($user->picture) ... 一样简单

因此,文件的保存已经由Stapler负责,裁剪是通过'pictureCropped' => '75x75#'配置自动完成的。这应该会删除足够多的代码,而不需要制作另一个方法。

希望这能有所帮助!