Ign*_*kis 0 php class helper symfony
我在我的Controller中有这个方法,多次调用indexAction().我应该保持它原样,还是应该为它和其他可重用方法创建Helper类(服务),因为我可以避免传递诸如此类$em情况的参数?我无法理解服务的背景以及何时使用它们很舒服.
public function getProfile($em, $username, $password) {
$dql = $em->createQuery('SELECT Profiles FROM ProjectProjectBundle:Profiles AS Profiles WHERE Profiles.email = :email AND Profiles.password = :password')
->setParameters(array(
'email' => $username,
'password' => $password
));
return $dql->getArrayResult();
}
Run Code Online (Sandbox Code Playgroud)
首先,要知道:你永远不应该,永远不会在你的控制器中拥有SQL/DQL.决不.
其次,你有几个选择,但我只想概述一个.我假设你已经定义了实体,所以让我们从基于它的选项开始.
告诉doctrine实体的存储库所在的学说
SRC /项目/ ProjectBundle /实体/ Profiles.php
/**
* @ORM\Table()
* @ORM\Entity(repositoryClass="Project\ProjectBundle\Entity\ProfilesRepository")
*/
class Profiles {}
Run Code Online (Sandbox Code Playgroud)创建ProfilesRepository类并使用自定义查找程序
SRC /项目/ ProjectBundle /实体/ ProfilesRepository.php
namespace Project\ProjectBundle\Entity;
use Doctrine\ORM\EntityRepository;
class ProfilesRepository extends EntityRepository
{
/**
* Find a Profiles entity with the given credentials
*
* @return \Project\ProjectBundle\Entity\Profiles|null
*/
public function findByCredentials($username, $password)
{
return $this->findBy(array('email' => $username, 'password' => $password ));
}
}
Run Code Online (Sandbox Code Playgroud)更新控制器中的便捷方法
/**
* Fetch a user's profile
*
* @return \Project\ProjectBundle\Entity\Profiles
*/
private function fetchProfile($username, $password)
{
try { // Exception-safe code is good!
$profilesRepo = $this->getDoctrine()->getEntityRepository('ProjectProjectBundle:Profiles');
return $profilesRepo->findByCredentials($username, $password);
}
catch (\Exception $e)
{
// Do whatever you want with exceptions
}
return null;
}
Run Code Online (Sandbox Code Playgroud)关于该提案的几点说明
getProfile(),fetchProfile()因为它更好地描述了该方法的作用.我也将它设为私有,因为这只是一种良好的安全编码实践.