Im seraching qua và không thể tìm thấy câu trả lời. Tôi có mô hình vai trò cơ sở dữ liệu trong ứng dụng của mình. Người dùng có thể có vai trò nhưng vai trò này phải được lưu trữ vào cơ sở dữ liệu.Symfony 2.0 nhận dịch vụ bên trong thực thể
Nhưng sau đó người dùng cần phải thêm vai trò mặc định từ cơ sở dữ liệu. Vì vậy, tôi đã tạo ra một dịch vụ:
<?php
namespace Alef\UserBundle\Service;
use Alef\UserBundle\Entity\Role;
/**
* Description of RoleService
*
* @author oracle
*/
class RoleService {
const ENTITY_NAME = 'AlefUserBundle:Role';
private $em;
public function __construct(EntityManager $em)
{
$this->em = $em;
}
public function findAll()
{
return $this->em->getRepository(self::ENTITY_NAME)->findAll();
}
public function create(User $user)
{
// possibly validation here
$this->em->persist($user);
$this->em->flush($user);
}
public function addRole($name, $role) {
if (($newrole = findRoleByRole($role)) != null)
return $newrole;
if (($newrole = findRoleByName($name)) != null)
return $newrole;
//there is no existing role
$newrole = new Role();
$newrole->setName($name);
$newrole->setRole($role);
$em->persist($newrole);
$em->flush();
return $newrole;
}
public function getRoleByName($name) {
return $this->em->getRepository(self::ENTITY_NAME)->findBy(array('name' => $name));
}
public function getRoleByRole($role) {
return $this->em->getRepository(self::ENTITY_NAME)->findBy(array('role' => $role));
}
}
tôi services.yml
là:
alef.role_service:
class: Alef\UserBundle\Service\RoleService
arguments: [%doctrine.orm.entity_manager%]
Và bây giờ tôi muốn sử dụng nó ở hai nơi: UserController
và User
thực thể. Làm thế nào tôi có thể nhận được chúng bên trong thực thể? Đối với bộ điều khiển tôi nghĩ rằng tôi chỉ cần:
$this->get('alef.role_service');
Nhưng làm cách nào để nhận dịch vụ bên trong thực thể?
Đó là giải pháp tốt nhất và câu trả lời chính xác nhất cho câu hỏi. Tôi ghét những câu trả lời như "bạn không thể", "đó là mẫu thiết kế quá sai" hoặc "Nó sẽ làm hỏng mọi thứ, bạn khốn kiếp!" được viết bởi rất kinh nghiệm. "Tệ hơn là (đôi khi) tốt hơn";) Cảm ơn một lần nữa. –
Đáng buồn thay, "mẫu thiết kế sai", "mô hình MCV", "Lớp kinh doanh riêng biệt", v.v. đi ra khỏi cửa sổ khi 'ông chủ' muốn thực hiện "ngay bây giờ". Cảm ơn câu trả lời @Kai, đó là những gì tôi đang tìm kiếm. –