创建服务的正确方法?

时间:2019-07-23 14:28:01

标签: symfony oop service

已经有一段时间我无法理解服务的含义,我的意思是我应该在代码中创建服务时使用Symfony吗?我对服务了解的东西是无状态的,我应该为可能在我的项目中多个地方使用的部分代码创建服务。但是我相信我不应该在控制器中加入逻辑。这可能会让我考虑将控制器逻辑放在单独的类中称为服务,但我不确定这是正确的。例如,最近我创建了如下服务类:

declare(strict_types=1);
namespace App\Service;
use App\Repository\ContactDoctrineRepository;
use App\Repository\RepositoryInterface;
use App\ValueObject\Email;
use App\ValueObject\Message;
use Doctrine\ORM\OptimisticLockException;
use Doctrine\ORM\ORMException;
use InvalidArgumentException;
use SplFileObject;
/**
 * Class ImportContractService
 * @package App\Service
 */
class ImportContactService
{
    /**
     * @var ContactDoctrineRepository
     */
    public $repository;
    /**
     * ContactService constructor.
     * @param RepositoryInterface $repository
     */
    public function __construct(RepositoryInterface $repository)
    {
        $this->repository = $repository;
    }
    /**
     * @param SplFileObject $file
     * @return array
     * @throws ORMException
     * @throws OptimisticLockException
     */
    public function addContacts(SplFileObject $file): array
    {
        $objects = [];
        $count = 0;
        foreach ($file as $row) {
            $count++;
            try {
                $objects[] = ['email' => new Email($row[0]), 'message' => new Message($row[1])];
            } catch (InvalidArgumentException $exception) {
                //skip invalid rows
                continue;
            }
        }
        if (count($objects) == 0) {
            throw new InvalidArgumentException('no valid row found, make sure you select a correct csv file');
        }
        $this->repository->storeAll($objects);
        return ['all' => $count, 'inserted' => count($objects)];
    }
}

我收到某人的反馈是技术面试官上课不对?那么,如果此代码错误,那是正确的呢?我应该如何从CSV文件导入数据,直接将此代码放入控制器?!

0 个答案:

没有答案