正确使用通用模型方法

时间:2016-06-20 20:38:30

标签: php laravel laravel-5.2

我是Laravel的新手并试图了解基本用法。

我的控制器中有以下与术语/分类模型相关的代码。

$taxonomy = Taxonomy::where('slug', '=', str_slug('brand'))->first();

if ( isset($taxonomy->id) ) {

  $term = $taxonomy->term()->firstOrCreate(array('slug' => str_slug($request->name)));

  $term->name = $request->name;

  $term->save();
}

我想让其他控制器可以使用它而不确定正确的位置。

我想过将它放在“addTerm”方法下的Taxonomy模型中,但是Taxonomy :: where()并不是正确的。

这样做的正确方法是什么?它应该在分类模型中还是在方法的辅助文件中?

2 个答案:

答案 0 :(得分:2)

从我的观点来看,并不是一种方法。我喜欢使用存储库模式并存储与sql相关的方法,以便我可以在整个应用程序中重用它们。

例如,https://bosnadev.com/2015/03/07/using-repository-pattern-in-laravel-5/解释了这一点,我发现这篇文章非常有用/有趣:http://dfg.gd/blog/decoupling-your-code-in-laravel-using-repositiories-and-services

答案 1 :(得分:1)

当我为自己解决这个问题时,我选择了辅助课程。我想让我的模型专注于数据结构,并在多个控制器之间共享某些活动。

以下代码是处理邮寄地址的示例。用例是几个其他实体将与一个或多个地址相关联。所有权通过多对多关系的中间表进行管理。

(*这是我第一次接触存储库模式,它看起来非常吸引人。我将进一步探索它。)

应用程序/助手/型号/ Address.php

<?php

namespace App\Helpers\Models;

use Illuminate\Validation\Factory as Validator;
use App\Models\Address as AddressModel;
use App\Exceptions\ValidatorException;

/**
 * Class Address
 *
 * @todo descriptive error messages
 * @package App\Helpers\Models
 */
class Address
{
    static $validation_rules = [
        'street_number' => 'required|string|max:255',
        'street_name' => 'string|max:255',
        'unit' => 'string|max:255',
        'city' => 'required|string|max:255',
        'state' => 'required|string|max:255',
        'postal_code' => 'required|string|max:10'
    ];

    static $validation_messages = [
        'street_number.required' => 'A street address is required.',
        'street_number.string' => 'A street address is required.',
        'street_number.max' => 'A street address is required.',
        'street_name.string' => 'A street address is required.',
        'street_name.max' => 'A street address is required.',
        'unit.string' => 'A street address is required.',
        'unit.max' => 'A street address is required.',
        'city.required' => 'A city is required.',
        'city.string' => 'A street address is required.',
        'city.max' => 'A street address is required.',
        'state.required' => 'A state is required.',
        'state.string' => 'A state is required.',
        'state.max' => 'A state is required.',
        'postal_code.required' => 'A zip code is required.',
        'postal_code.string' => 'A zip code is required.',
        'postal_code.max' => 'A zip code is required.'
    ];


    public static function store(array $data, array $options = array())
    {
        $validator = Validator::make($data, self::$validation_rules, self::$validation_messages);
        if ($validator->fails()) {
            throw new ValidatorException($validator);
        }

        $address = new AddressModel();

        $address->fill($data);

        return $address;
    }

    public static function update(array $data, array $options = array())
    {
        // TODO: Implement update() method.
    }

    public static function destroy($id, array $options = array())
    {
        // TODO: Implement destroy() method.
    }
}

应用程序/异常/ ValidatorException.php

<?php

namespace App\Exceptions;

use \Exception;

class ValidatorException extends Exception
{
    protected $validator;

    // Redefine the exception so validator is captured
    public function __construct($validator, $message = null, $code = 0, Exception $previous = null) {
        // some code
        $this->validator = $validator;

        if (!$message) {
            $message = join(' ', $validator->getMessageBag()->all());
        }

        // make sure everything is assigned properly
        parent::__construct($message, $code, $previous);
    }

    public function getValidator()
    {
        return $this->validator;
    }
}