提问人:Ali monji 提问时间:3/4/2018 最后编辑:Ali monji 更新时间:9/26/2018 访问量:1795
Symfony 未定义索引
Symfony Undefined index
问:
我正在创建一个应用程序,该应用程序从不同的来源(DB、XML、JSON 等)获取和搜索产品名称(对于此代码,我仅使用数据库进行测试),我的想法是为此创建一个接口。 我创建了接口 ProductRepositoryInterface 和类 DoctrineProductRepository,然后将它们声明为服务。 在我的控制器中,我调用了搜索函数,并将产品名称称为 param。 这是我的界面 ProductRepositoryInterface :
namespace Tyre\TyreBundle\Repository;
interface ProductRepositoryInterface
{
function search(string $needle);
}
我的界面 DoctrineProductRepository:
namespace Tyre\TyreBundle\Repository;
class DoctrineProductRepository implements ProductRepositoryInterface
{
public function __constructor(EntityManager $em)
{
$this->em = $em;
}
public function search(string $needle)
{
$repository = $this->em->getRepository('TyreTyreBundle:Products');
$query = $repository->createQueryBuilder('u')
->where("u.name LIKE '%".$needle."%' or u.manufacturer LIKE '%".$needle."%'")
->getQuery();
return $query->getArrayResult();
}
}
我的服务.yml
services:
Tyre\TyreBundle\Repository\DoctrineProductRepository:
class: Tyre\TyreBundle\Repository\DoctrineProductRepository
Tyre\TyreBundle\Repository\ProductRepositoryInterface:
class: Tyre\TyreBundle\Repository\ProductRepositoryInterface
最后是我的控制器:
命名空间 Tyre\TyreBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Tyre\TyreBundle\Repository\DoctrineProductRepository;
use Tyre\TyreBundle\Repository\ProductRepositoryInterface;
class DefaultController extends Controller
{
public function indexAction()
{
return $this->render('TyreTyreBundle:Default:search.html.twig');
}
public function searchAction(Request $request) {
$repositoryMap = [
'db' => DoctrineProductRepository::class,
];
$serviceName = $repositoryMap[$request->get('db')]; /***This is Line 56 ***/
/** @var ProductRepositoryInterface */
$repository = $this->get($serviceName);
$results = $repository->search($request->get('search_for'));
return $this->render('TyreTyreBundle:Default:detail.html.twig', array('results' => $results));
}
public function detailAction()
{
//forward the user to the search page when he tries to access directly to the detail page
return $this->render('TyreTyreBundle:Default:search.html.twig');
}
}
但是我收到一个错误:
编辑
当我尝试 http://localhost:8000/search?db=db 时,我收到其他错误(我var_dumped $repositoryMap):点击查看
我错过了什么吗?
答:
1赞
Prakash S
9/26/2018
#1
“ContextErrorException”的原因是:
$request->get('search_for')
为空,因为您没有在该键的 URL 中传递任何内容。除了“db”之外,还要传递“search_for”,例如:
评论
$request->get('db')
$repositoryMap
http://localhost/index?db=db