I have a custom repository in my Symfony's project and I want use like a search tool. My project' structure is the following:
P.D. UPDATED Question and code
-Manager:
* BaseManager.php
* MyEntityManager.php
-Repository:
* BaseRepository.php
* MyEntityRepository.php
Well, I want access to my custom repository and use the following method findByTitle, which method should return an array with objects which description field be similar. I put a simple print (var_dump of the term entered) inside of my function to see if my browser shows it, but it isn't showed yet...
My BaseManager:
<?php
namespace AppBundle\Manager;
use AppBundle\Repository\BaseRepository;
class BaseManager
{
/**
* #var BaseRepository
*/
protected $repo;
/**
* #param BaseRepository $repo
*/
public function __construct(BaseRepository $repo)
{
$this->repo = $repo;
}
/**
* #param $model
* #return bool
*/
public function create($model)
{
return $this->repo->create($model);
}
/**
* #param CrudModel $model
* #return bool
*/
public function update($model)
{
return $this->repo->save($model);
}
/**
* #param CrudModel $model
* #return bool
*/
public function delete($model)
{
return $this->repo->delete($model);
}
/**
* #param $id
* #return null|object
*/
public function getOneById($id)
{
return $this->repo->findOneById($id);
}
/**
* #return array
*/
public function all()
{
return $this->repo->all();
}
}
MyEntityManager:
<?php
namespace AppBundle\Manager;
use AppBundle\Repository\MyEntityRepository;
use AppBundle\Entity\MyEntity;
/**
* Class MyEntityManager
* #package AppBundle\Manager
*/
class MyEntityManager extends BaseManager{
public function findByTitle($title){
echo '<h1>flux of code here</h1>';
return $this->repo->findByTitle($title);
}
public function findSimilars($term){
echo '<h1>flux of code here</h1>';
return $this->repo->findSimilars($term);
}
}
BaseRepository:
<?php
namespace AppBundle\Repository;
use Doctrine\ORM\EntityRepository;
abstract class BaseRepository extends EntityRepository
{
public function create($model, $autoFlush = true)
{
return $this->insert($model,$autoFlush);
}
public function save($model, $autoFlush = true)
{
return $this->insert($model,$autoFlush);
}
public function delete($model)
{
try{
$this->getEntityManager()->remove($model);
$this->getEntityManager()->flush();
return true;
}catch (\Exception $e){
echo $e->getMessage();
}
}
public function findOneById($id)
{
return $this->findOneBy(array('id' => $id));
}
public function all()
{
return $this->findAll();
}
private function insert($model, $autoFlush = true)
{
$this->getEntityManager()->persist($model);
if ($autoFlush) {
$this->getEntityManager()->flush();
return true;
}
}
}
MyEntityRepository:
<?php
namespace AppBundle\Repository;
use Doctrine\ORM\EntityRepository;
/**
* Class MyEntityRepository
* #package AppBundle\Repository
*/
class MyEntityRepository extends BaseRepository{
private function findById($id){
$query = $this->createQueryBuilder('myentity')
->where('myentity.id = :id')
->setParameter('id', $id)
->getQuery();
$myentity = $query->getResult();
return $myentity;
}
private function findByTitle($term){
echo '<h1>';
var_dump($term);
echo '</h1>',
$query = $this->createQueryBuilder('myentity')
->andwhere('myentity.description = :description')
->setParameter('description', $term)
->getQuery();
$myentity = $query->getResult();
return $myentity;
}
}
The beginning of MyEntity:
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
/**
* #ORM\Table(name="myentity")
* #ORM\Entity
* #ORM\Entity(repositoryClass="AppBundle\Repository\MyEntityRepository")
*/
class MyEntity {
......
My services.yml:
parameters:
app.myentity.repository.class: AppBundle\Repository\MyEntityRepository
app.myentity.manager.class: AppBundle\Manager\MyEntityManager
services:
app.myentity.repository:
class: %app.myentity.repository.class%
public: true
factory_service: doctrine.orm.entity_manager
factory_method: getRepository
arguments: [ AppBundle\Entity\MyEntity ]
app.myentity.manager:
class: %app.myentity.manager.class%
arguments: [#app.myentity.repository]
And I'm calling my service in the following way:
public function searchAction(Request $request, $term){
$manager = $this->get('app.myentity.manager');
$result = $manager->findByTitle($term);
echo '<h5>';
var_dump($result);
echo '</h5>';
....
}
Just a guess, as your question is far from being clear (esp. the last paragraph): did you only register the service, or did you also tell Symfony to use the repository for the entity (presumably MyEntity)? For instance, using annotations, you’d need something like this:
#ORM\Entity(repositoryClass="The\RepositoryClass")
The problem was that I declared my function as private instead of public
private function findByTitle($term){
instead of
public function findByTitle($term){
Related
I'm trying to write a unit test for the startedAt() method using mocks however the problem I'm facing is that I don't think I can access the builder instance from inside that startedAt() method.
To test the startedAt() method I created a fixture class called ExampleFilters and had it extend the parent class of Filters. Inside of the ExampleFilters class I import the FiltersByStartDate trait.
Does anyone have any suggestions on how I can access the builder property from the FiltersByStartDate trait?
Any ideas on this?
<?php
namespace App\Filters\Concerns;
trait FiltersByStartDate
{
/**
* Filter a query to include models of a specific date started.
*
* #param array $startedAt
* #return \Illuminate\Database\Eloquent\Builder
*/
public function startedAt($startedAt)
{
if (isset($startedAt[1])) {
$this->builder->whereHas('currentEmployment', function ($query) use ($startedAt) {
$query->whereBetween('started_at', [
$startedAt[0],
$startedAt[1]
]);
});
} else {
$this->builder->whereHas('currentEmployment', function ($query) use ($startedAt) {
$query->whereDate('started_at', $startedAt[0]);
});
}
return $this->builder;
}
}
<?php
namespace Tests\Fixtures;
use App\Filters\Concerns\FiltersByStartDate;
use App\Filters\Filters;
class ExampleFilters extends Filters
{
use FiltersByStartDate;
}
<?php
namespace App\Filters;
use Illuminate\Http\Request;
abstract class Filters
{
/**
* #var \Illuminate\Http\Request
*/
protected $request;
/**
* The Eloquent builder.
*
* #var \Illuminate\Database\Eloquent\Builder
*/
protected $builder;
/**
* Registered filters to operate upon
*
* #var array
*/
protected $filters = [];
/**
* Create a new class instance.
*
* #param \Illuminate\Http\Request $request
*/
public function __construct(Request $request)
{
$this->request = $request;
}
/**
* Apply the filters.
*
* #param \Illuminate\Database\Eloquent\Builder $builder
* #return \Illuminate\Database\Eloquent\Builder
*/
public function apply($builder)
{
$this->builder = $builder;
foreach ($this->getFilters() as $filter => $value) {
if (method_exists($this, $filter)) {
$this->$filter($value);
}
}
return $this->builder;
}
/**
* Fetch all relevant filters from the request.
*
* #return array
*/
public function getFilters()
{
return array_filter($this->request->only($this->filters));
}
}
<?php
namespace Tests\Unit\Filters\Concerns;
use Illuminate\Database\Query\Builder;
use Tests\Fixtures\ExampleFilters;
use Tests\TestCase;
/*
* #group filters
*/
class FiltersByStartDateTest extends TestCase
{
/* #var Tests\Fixtures\ExampleFilters */
protected $subject;
public function setUp(): void
{
$this->subject = app(ExampleFilters::class);
}
/** #test */
public function models_can_be_filtered_by_their_start_date()
{
// $this->markTestIncomplete();
$dateSet = ['2020-01-01 00:00:00'];
$mock = \Mockery::mock(Builder::class)
->shouldReceive('whereHas', \Mockery::any())
->shouldReceive('whereDate')
->withArgs(['started_at', $dateSet])
->once()
->andReturn(true)
->getMock();
dd($this->subject->startedAt($dateSet));
$builderMockFromDate = $this->subject->startedAt($dateSet);
$this->assertSame($builderMockFromDate, $mock);
}
}
I created Document manually, and tried to save data using persist.its show me following error.
The class 'Kdm\\SettingBundle\\Document\\Discount' was not found in the chain configured namespaces FOS\\UserBundle\\Entity, Ivory\\GoogleMapBundle\\Entity at
/var/www/project/vendor/doctrine/common/lib/Doctrine/Common/Persistence/Mapping/MappingException.php:37)"}
Here is my document file Discount.php
<?php
namespace Kdm\SettingBundle\Document;
use Doctrine\ODM\MongoDB\Mapping\Annotations as MongoDB;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\Validator\Constraints as Assert;
/**
* Discount
* #MongoDB\Document(repositoryClass="Kdm\SettingBundle\Repository\SettingRepository")
*/
class Discount
{
/**
* #MongoDB\Id(strategy="auto")
*/
protected $id;
/**
* #MongoDB\Field(type="integer")
*/
protected $value;
/**
* Get id
*
* #return string $id
*/
public function getId()
{
return $this->id;
}
/**
* #param integer $value
*/
public function setValue($value)
{
$this->value = $value;
}
/**
* #return integer
*/
public function getValue()
{
return $this->value;
}
}
Here is my SettingController.php
<?php
namespace Kdm\SettingBundle\Controller;
use Kdm\KdmBundle\Controller\RefController as KdmController;
use Kdm\SettingBundle\Document\Discount as Setting;
use Symfony\Component\HttpFoundation\Request;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
/**
* #Route("/setting")
*/
class SettingController extends KdmController
{
/**
* Constructor
*/
public function __construct()
{
parent::__construct('Kdm', 'Setting', 'setting','Discount');
}
/**
* #Route
* (
* path="/",
* name="kdm_setting"
* )
* #Template("::KdmSetting/Front/index.html.twig")
*/
public function indexAction()
{
$setting = new Setting();
$setting->setValue('5');
$em = $this->getDoctrine()->getManager();
$em->persist($setting);
$em->flush();
$form = $this->createFormBuilder($setting)
->add('value','integer')
->add('save','submit')
->getForm();
return array(
'form' => $form->createView()
);
}
}
i try to solve this error since last 2 days :( Can you help?
I create service for add formType then persist object and in controller I invoke data but I have error shown on below image:
in controller i extend class abstractController content getHandler and I have view newskill.html.twig
Code SkillController.php:
<?php
namespace AppBundle\Controller\Condidate;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use AppBundle\Entity\Skill;
use AppBundle\Controller\AbstractController;
use AppBundle\Form\SkillType;
/**
*Class SkillController.
*/
class SkillController extends AbstractController
{
/**
*function handler.
*/
protected function getHandler(){
//var_dump('test');
}
/**
*function addSkill
* #param Request $request
* #return \Symfony\Component\Form\Form The form
*/
public function addSkillAction(Request $request) {
$skill = $this->getHandler()->post();
if ($skill instanceof \AppBundle\Entity\Skill) {
return $this->redirectToRoute('ajouter_info');
}
return $this->render('skills/newskill.html.twig', array(
'form' => $form->createView(),));
}
}
Code SkillHandler.php:
<?php
namespace AppBundle\Handler;
use AppBundle\Handler\HandlerInterface;
use Symfony\Component\HttpFoundation\Request;
use AppBundle\Entity\Skill;
use Doctrine\ORM\EntityManager;
use Symfony\Component\DependencyInjection\Container;
use Symfony\Component\Form\formFactory;
/**
* SkillHandler.
*/
class SkillHandler implements HandlerInterface {
/**
*
* #var EntityManager
*/
protected $em;
/**
*
* #var formFactory
*/
private $formFactory;
/**
*function construct.
*/
public function __construct(EntityManager $entityManager, formFactory $formFactory)
{
$this->em = $entityManager;
$this->formFactory = $formFactory;
}
/**
*function post
*/
public function post(array $parameters, array $options = []) {
$form = $this->formFactory->create(\AppBundle\Form\SkillType::class, $object, $options);
$form->submit($parameters);
if ($form->isValid()) {
$skill = $form->getData();
$this->persistAndFlush($skill);
return $skill;
}
return $form->getData();
}
/**
*function persisteAndFlush
*/
protected function persistAndFlush($object) {
$this->em->persist($object);
$this->em->flush();
}
/**
*function get
*/
public function get($id){
throw new \DomainException('Method SkillHandler::get not implemented');
}
/**
*function all
*/
public function all($limit = 10, $offset = 0){
throw new \DomainException('Method SkillHandler::all not implemented');
}
/**
*function put
*/
public function put($resource, array $parameters, array $options){
throw new \DomainException('Method SkillHandler::put not implemented');
}
/**
*function patch
*/
public function patch($resource, array $parameters, array $options){
throw new \DomainException('Method SkillHandler::patch not implemented');
}
/**
*function delete
*/
public function delete($resource){
throw new \DomainException('Method SkillHandler::delete not implemented');
}
}
code services.yml:
skill_add:
class: AppBundle\Handler\SkillHandler
arguments:
- "#doctrine.orm.entity_manager"
- "#form.factory"
public: true
Any help would be appreciated.
Your $this->getHandler() retruns null.
Solution can be checking if $this->getHandler() doesn't return null in first place.
if (!$this->getHandler()) {
throw new \Exception(sprintf('Handler cannot be null')
} else {
$skill = $this->getHandler()->post();
}
Try this, firstly you should take your handler into getHandler() method at your Controller.
protected function getHandler(){
return $this->get('skill_add');
}
Hello I have a problem with MaddHatter\LaravelFullcalendar\Calendar. I already try to look documentation and search in other question in stackoverflow but still didn't find the solution.
This is my eror :
Type error: Argument 1 passed to
MaddHatter\LaravelFullcalendar\Calendar::addEvent() must implement
interface MaddHatter\LaravelFullcalendar\Event, array given, called in
D:\XAMPP\htdocs\isei\vendor\laravel\framework\src\Illuminate\Support\Facades\Facade.php
on line 221
EventController :
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\EventModel;
use App\Branch;
use Calendar;
use MaddHatter\LaravelFullcalendar\Event;
class EventController extends Controller
{
public function getIndex()
{
$event = [];
$data = EventModel::all();
if($data->count())
{
foreach ($data as $key => $value)
{
$event[] = Calendar::event(
$value->title,
true,
new \DateTime($value->start_date),
new \DateTime($value->end_date.' +1 day')
);
}
}
$calendar = \Calendar::addEvent($event);
return view('event', compact('calendar'));
}
}
Event Model :
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class EventModel extends Model implements \MaddHatter\LaravelFullcalendar\IdentifiableEvent
{
protected $table = 'event';
protected $fillable = [
'id_branch','title','start_date','end_date'
];
public function cabang()
{
return $this->hasOne('App\Branch', 'id', 'id_branch');
}
protected $dates = ['start', 'end'];
/**
* Get the event's id number
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Get the event's title
*
* #return string
*/
public function getTitle()
{
return $this->title;
}
/**
* Is it an all day event?
*
* #return bool
*/
public function isAllDay()
{
return (bool)$this->all_day;
}
/**
* Get the start time
*
* #return DateTime
*/
public function getStart()
{
return $this->start;
}
/**
* Get the end time
*
* #return DateTime
*/
public function getEnd()
{
return $this->end;
}
}
try to change:
use MaddHatter\LaravelFullcalendar\Event;
at your EventController to this:
use MaddHatter\LaravelFullcalendar\Facades\Calendar;
add s to addEvent
$calendar = \Calendar::addEvents($event);
This function is in helper I am using zf2 version 2.4 I am beginner in zend please help me.
I tried this:
function getUrlArray(){
$helperUrl = new Url(); // use Zend\View\Helper\Url;
$op = $helperUrl->url();
print_r($op);
}
I am getting this error:
Fatal error: Call to undefined method Zend\View\Helper\Url::url()
Try this ViewHelper :
<?php
namespace YourNamespace\View\Helper\Service;
use YourNamespace\View\Helper\CurrentUri;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
class CurrentUriFactory implements FactoryInterface
{
/**
* #param ServiceLocatorInterface $serviceLocator
* #return CurrentUri
*/
public function createService(ServiceLocatorInterface $serviceLocator)
{
$helper = new CurrentUri();
$helper->setRequest($serviceLocator->getServiceLocator()->get('Request'));
return $helper;
}
}
<?php
namespace YourNamespace\View\Helper;
use Zend\Stdlib\RequestInterface;
use Zend\View\Helper\AbstractHelper;
/**
* Helper: $this->currentUri();
*/
class CurrentUri extends AbstractHelper
{
/**
* #var \Zend\Http\PhpEnvironment\Request
*/
protected $request;
/**
* #return string
* #see \Zend\Http\PhpEnvironment\Request
* #see \Zend\Uri\Uri
*/
public function __invoke()
{
return $this->getRequest()->getUri()->toString();
}
/**
* #return \Zend\Http\PhpEnvironment\Request
*/
public function getRequest()
{
return $this->request;
}
/**
* #param RequestInterface $request
* #return CurrentUri
*/
public function setRequest(RequestInterface $request)
{
$this->request = $request;
return $this;
}
}