I have a one-to-many self referencing entity. Everything works fine as long as the parent value is set to null. When I set the parent item to something actually in the list, I get the error:
Class integer does not exist
500 Internal Server Error - ReflectionException
Here is the code for my entity:
<?php
namespace WorkRecorder\WorkBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
/**
* #ORM\Entity(repositoryClass="WorkRecorder\WorkBundle\Repository\WorkRepository")
* #ORM\Table(name="strategyUsed")
*/
class StrategyUsed
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ORM\Column(type="integer")
*/
protected $sortOrder;
/**
* #ORM\Column(type="string", length=50)
*/
protected $name;
/**
* #ORM\Column(type="text")
*/
protected $description;
/**
* #ORM\OneToMany(targetEntity="StrategyUsed", mappedBy="parent")
*/
private $children;
/**
* #ORM\ManyToOne(targetEntity="StrategyUsed", inversedBy="children")
* #ORM\JoinColumn(name="parent_id", referencedColumnName="id")
*/
private $parent;
public function __construct() {
$this->children = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
*/
public function setName($name)
{
$this->name = $name;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set description
*
* #param text $description
*/
public function setDescription($description)
{
$this->description = $description;
}
/**
* Get description
*
* #return text
*/
public function getDescription()
{
return $this->description;
}
/**
* Set sortOrder
*
* #param integer $sortOrder
*/
public function setSortOrder(\integer $sortOrder)
{
$this->sortOrder = $sortOrder;
}
/**
* Get sortOrder
*
* #return integer
*/
public function getSortOrder()
{
return $this->sortOrder;
}
/**
* Add children
*
* #param WorkRecorder\WorkBundle\Entity\StrategyUsed $children
*/
public function addStrategyUsed(\WorkRecorder\WorkBundle\Entity\StrategyUsed $children)
{
$this->children[] = $children;
}
/**
* Get children
*
* #return Doctrine\Common\Collections\Collection
*/
public function getChildren()
{
return $this->children;
}
/**
* Set parent
*
* #param WorkRecorder\WorkBundle\Entity\StrategyUsed $parent
*/
public function setParent(\WorkRecorder\WorkBundle\Entity\StrategyUsed $parent)
{
$this->parent = $parent;
}
/**
* Get parent
*
* #return WorkRecorder\WorkBundle\Entity\StrategyUsed
*/
public function getParent()
{
return $this->parent;
}
}
What am I doing wrong?
You can't type hint on a scalar type (integer/string/boolean etc) in PHP. e.g.
public function setSortOrder(\integer $sortOrder)
Should be:
public function setSortOrder($sortOrder)
You can validate the type of the value within the method and perhaps throw an InvalidArgumentException if passed something that isn't an integer.
Related
I have a question.
I have 2 entity
/**
* #ORM\Entity
* #ORM\Table(name="call_center")
*/
class Call {
/**
* #ORM\GeneratedValue(strategy="AUTO")
* #ORM\Id
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\OneToMany(targetEntity="Number", mappedBy="number")
* #ORM\Column(type="string")
*/
private $number;
/**
* #ORM\Column(type="string")
*/
private $value;
......
getters setters
/**
* #ORM\Entity
* #ORM\Table(name="number")
*/
class Number {
/**
* #ORM\GeneratedValue(strategy="AUTO")
* #ORM\Id
* #ORM\Column(type="integer")
*
*/
private $id;
/**
* #ORM\ManyToOne(targetEntity="Call", inversedBy="number")
* #ORM\JoinColumn(nullable=false)
*/
private $number;
/**
* #ORM\Column(type="string")
*/
private $link;
And I would like to show my data in controller.
This is my controller
class DefaultController extends Controller
{
/**
* #Route("/pl/", name="homepage")
*/
public function indexAction(Request $request)
{
$em = $this->getDoctrine()->getRepository('AppBundle:Call')->findAll();
foreach ($em as $name) {
switch(1) {
case $name->getNumber():
echo $name->getValue();
echo $name->getLink(); <----PROBLEME
break;
default:
break;
}
}
return $this->render('default/index.html.twig', array(
'em' => $name
));
}
}
Data with entity call displayed but I don't know how dipsplay data from Number (getLink()). The problem is that I have a loop in which I have to display for a particular value relationship. Probably I have to create repository for entity?
Entity Call
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set number
*
* #param string $number
*
* #return Call
*/
public function setNumber($number)
{
$this->number = $number;
return $this;
}
/**
* Get number
*
* #return string
*/
public function getNumber()
{
return $this->number;
}
/**
* Set value
*
* #param string $value
*
* #return Call
*/
public function setValue($value)
{
$this->value = $value;
return $this;
}
/**
* Get value
*
* #return string
*/
public function getValue()
{
return $this->value;
}
entity Number
/**
* Set number
*
* #param \AppBundle\Entity\Call $number
*
* #return Number
*/
public function setNumber(\AppBundle\Entity\Call $number)
{
$this->number = $number;
return $this;
}
/**
* Get number
*
* #return \AppBundle\Entity\Call
*/
public function getNumber()
{
return $this->number;
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set link
*
* #param string $link
*
* #return Number
*/
public function setLink($link)
{
$this->link = $link;
return $this;
}
/**
* Get link
*
* #return string
*/
public function getLink()
{
return $this->link;
}
Maybe you have a string because you tell doctrine to put a string ?
remove the following annotation from your relation :
#ORM\Column(type="string")
Have you tried to access it via $name->getNumber()->getLink() ?
as pointed out below, by tny, you should fix your annotations, or the above will not work, as getNumber() is currently returning a string instead of a Number instance
I have two entities as follows:
<?php
// src/coreBundle/Entity/model.php
namespace coreBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use coreBundle\Entity\brand;
/**
*#ORM\Entity
*#ORM\Table(name="model")
*/
class model
{
/**
* #ORM\ManyToOne(targetEntity="coreBundle\Entity\brand", inversedBy="models")
* #ORM\JoinColumn(name="brand_id", referencedColumnName="id")
*/
private $brands;
/**
* #ORM\Column(type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
public $id;
/**
*#ORM\Column(type="integer")
*/
public $brand_id;
/**
*#ORM\Column(type="string", length=100)
*/
private $name;
/**
*#ORM\Column(type="string", length=100)
*/
private $image_url;
/**
*#ORM\Column(type="string", length=200)
*/
private $comment;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set brandId
*
* #param integer $brandId
*
* #return model
*/
public function setBrandId($brandId)
{
$this->brand_id = $brandId;
return $this;
}
/**
* Get brandId
*
* #return integer
*/
public function getBrandId()
{
return $this->brand_id;
}
/**
* Set name
*
* #param string $name
*
* #return model
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set imageUrl
*
* #param string $imageUrl
*
* #return model
*/
public function setImageUrl($imageUrl)
{
$this->image_url = $imageUrl;
return $this;
}
/**
* Get imageUrl
*
* #return string
*/
public function getImageUrl()
{
return $this->image_url;
}
/**
* Set comment
*
* #param string $comment
*
* #return model
*/
public function setComment($comment)
{
$this->comment = $comment;
return $this;
}
/**
* Get comment
*
* #return string
*/
public function getComment()
{
return $this->comment;
}
/**
* Set brands
*
* #param \coreBundle\Entity\brand $brands
*
* #return model
*/
public function setBrands(\coreBundle\Entity\brand $brands = null)
{
$this->brands = $brands;
return $this;
}
/**
* Get brands
*
* #return \coreBundle\Entity\brand
*/
public function getBrands()
{
return $this->brands;
}
}
And Second one is as follows:
<?php
// src/coreBundle/Entity/brand.php
namespace coreBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use coreBundle\Entity\model;
use Doctrine\Common\Collections\ArrayCollection;
/**
*#ORM\Entity
*#ORM\Table(name="brand")
*/
class brand
{
/**
* ORM\OneToMany(targetEntity="coreBundle\Entity\model", mappedBy="brands")
*/
private $models;
public function __construct()
{
$this->models = new ArrayCollection();
}
/**
* #ORM\Column(type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
public $id;
/**
*#ORM\Column(type="string", length=100)
*/
private $name;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
*
* #return brand
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
}
"model" has a ManyToOne relationship with "brand"
I am having issues of schema validation,
*The association coreBundle\Entity\model#brands refers to the inverse side field coreBundle\Entity\brand#models which does not exist
Can you tell what am I doing wrong, Thanks in advance.
In case your still wondering after 3 hours of agony, your missing the # in #ORM\OneToMany (brand.php).
I am learning code testing (TDD) and wondering what should be tested for simple entities in Symfony?
From official documentation:
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Category
*
* #ORM\Table(name="category")
* #ORM\Entity(repositoryClass="AppBundle\Repository\CategoryRepository")
*/
class Category
{
/**
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\Column(name="name", type="string", length=255)
*/
private $name;
/**
* #ORM\OneToMany(targetEntity="Product", mappedBy="category")
*/
private $products;
/**
* Constructor
*/
public function __construct()
{
$this->products = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
*
* #return Category
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Add product
*
* #param \AppBundle\Entity\Product $product
*
* #return Category
*/
public function addProduct(\AppBundle\Entity\Product $product)
{
$this->products[] = $product;
return $this;
}
/**
* Remove product
*
* #param \AppBundle\Entity\Product $product
*/
public function removeProduct(\AppBundle\Entity\Product $product)
{
$this->products->removeElement($product);
}
/**
* Get products
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getProducts()
{
return $this->products;
}
}
Second:
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
* #ORM\Table(name="product")
*/
class Product
{
/**
* #ORM\Column(type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\Column(type="string", length=100)
*/
private $name;
/**
* #ORM\Column(type="decimal", scale=2)
*/
private $price;
/**
* #ORM\Column(type="text")
*/
private $description;
/**
* #ORM\ManyToOne(targetEntity="Category", inversedBy="products")
* #ORM\JoinColumn(name="category_id", referencedColumnName="id")
*/
private $category;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
*
* #return Product
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set price
*
* #param string $price
*
* #return Product
*/
public function setPrice($price)
{
$this->price = $price;
return $this;
}
/**
* Get price
*
* #return string
*/
public function getPrice()
{
return $this->price;
}
/**
* Set description
*
* #param string $description
*
* #return Product
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description
*
* #return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Set category
*
* #param \AppBundle\Entity\Category $category
*
* #return Product
*/
public function setCategory(\AppBundle\Entity\Category $category = null)
{
$this->category = $category;
return $this;
}
/**
* Get category
*
* #return \AppBundle\Entity\Category
*/
public function getCategory()
{
return $this->category;
}
}
I thought I had to create an Entity folder and within CategoryTest file:
namespace Tests\AppBundle\Entity;
use AppBundle\Entity\Tag;
use AppBundle\Form\DataTransformer\TagArrayToStringTransformer;
use Doctrine\Common\Persistence\ObjectManager;
use Doctrine\ORM\EntityRepository;
class CategoryTest extends \PHPUnit\Framework\TestCase
{
public function testGetName()
{
$category = new \AppBundle\Entity\Category();
$category->setName('test');
$this->assertSame('test', $category->getName());
}
}
So... In TDD I should testing all fields? For Product entity I should testing name, price and description?
If yes, how to deal with refactoring? In these cases I must use in all methods "$product = new Product();";
For a name field I might need to do another test? What?
Should I also test relationships or do it in functional tests?
It is a good practice to Entities have no (complex) logic inside. In fact it should be just representing your model. And since there is no logic, there is not much to test actually. When you check Symfony Demo app you will find no tests for entities and I believe it is done this way intentionally.
In case your application is not the only one using database I would consider writing functional tests for entities which will ensure you that someone else did not change database structure (for example by dropping column in table) without letting you know. One of possible ways to achieve that is running a simple query on table (entity) you are testing:
public function checkEntityDefinition($entityName)
{ $this->em->getRepository($entityName)
->createQueryBuilder('t')
->setMaxResults(1)
->getQuery()
->getArrayResult();
}
There are no assertion here but this will throw an exception when Entity definition does not match database
I'm working my way through Symfony trying to learn how it all fits together and I'm working on the admin section.
Right now I'm putting together an admin form for a Show Entity which will reference a section entity (so this show belongs in that section, etc). Every other field in the form saves EXCEPT for the related entity choice field.
This is the ShowAdmin class
<?php
namespace AppBundle\Admin;
use Sonata\AdminBundle\Admin\AbstractAdmin;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Form\FormMapper;
use Nelmio\ApiDocBundle\Tests\Fixtures\Form\EntityType;
class ShowAdmin extends AbstractAdmin {
protected function configureFormFields(FormMapper $formMapper)
{
$formMapper->add('title', 'text')
->add('shortname', 'text')
->add('section_id', EntityType::class, array(
'class' => 'AppBundle:SectionEntity',
'choice_label' => 'section_title',
))
->add('logo', 'text')
->add('description', 'textarea')
->add('status', 'integer');
}
protected function configureDatagridFilters(DatagridMapper $datagridMapper)
{
$datagridMapper->add('title');
$datagridMapper->add('shortname');
}
protected function configureListFields(ListMapper $listMapper)
{
$listMapper->addIdentifier('title');
$listMapper->add('shortname', 'text');
}
}
This is the ShowEntity
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
* #ORM\Table(name="shows")
*/
class ShowEntity {
function __construct() {
$this->children = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* #ORM\Column(type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\Column(type="string", length=100)
*/
private $title;
/**
* #ORM\Column(type="string", length=100)
*/
private $shortname;
/**
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\SectionEntity")
*/
private $section;
/**
* #ORM\Column(type="string", length=255)
*/
private $logo;
/**
* #ORM\Column(type="text")
*/
private $description;
/**
* #ORM\Column(type="integer")
*/
private $status;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set title
*
* #param string $title
*
* #return ShowEntity
*/
public function setTitle($title)
{
$this->title = $title;
return $this;
}
/**
* Get title
*
* #return string
*/
public function getTitle()
{
return $this->title;
}
/**
* Set sectionId
*
* #param integer $sectionId
*
* #return ShowEntity
*/
public function setSectionId($sectionId)
{
$this->section_id = $sectionId;
return $this;
}
/**
* Get sectionId
*
* #return integer
*/
public function getSectionId()
{
return $this->section_id;
}
/**
* Set logo
*
* #param string $logo
*
* #return ShowEntity
*/
public function setLogo($logo)
{
$this->logo = $logo;
return $this;
}
/**
* Get logo
*
* #return string
*/
public function getLogo()
{
return $this->logo;
}
/**
* Set description
*
* #param string $description
*
* #return ShowEntity
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description
*
* #return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Set status
*
* #param integer $status
*
* #return ShowEntity
*/
public function setStatus($status)
{
$this->status = $status;
return $this;
}
/**
* Get status
*
* #return integer
*/
public function getStatus()
{
return $this->status;
}
/**
* Set shortname
*
* #param string $shortname
*
* #return ShowEntity
*/
public function setShortname($shortname)
{
$this->shortname = $shortname;
return $this;
}
/**
* Get shortname
*
* #return string
*/
public function getShortname()
{
return $this->shortname;
}
}
And this is the SectionEntity
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* SectionEntity
*
* #ORM\Table(name="section_entity")
* #ORM\Entity(repositoryClass="AppBundle\Repository\SectionEntityRepository")
*/
class SectionEntity
{
protected $section_id;
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\Column(type="text")
*/
private $section_title;
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set sectionTitle
*
* #param string $sectionTitle
*
* #return SectionEntity
*/
public function setSectionTitle($sectionTitle)
{
$this->section_title = $sectionTitle;
return $this;
}
/**
* Get sectionTitle
*
* #return string
*/
public function getSectionTitle()
{
return $this->section_title;
}
/**
* Get string
*/
public function __toString() {
return $this->section_title;
}
function __construct() {
$this->section_id = new \Doctrine\Common\Collections\ArrayCollection();
}
}
Any help would be greatly appreciated, I know it's probably something super simple that I'm just not seeing.
Thanks.
(optional) Rename ShowEntity::$section into ShowEntity::$sections to highlight sections is a collection but not a single entity.
Set ShowEntity __construct method body to:
$this->sections = new \Doctrine\Common\Collections\ArrayCollection();
At ShowAdmin::configureFormFields rename
->add('section_id', EntityType::class, array(
into
->add('section', EntityType::class, array(
You should use direct reference to the relation instead of id.
Remove SectionEntity::__construct method, it has no sense.
Remove protected $section_id; from SectionEntity.
Change public function setSectionId($sectionId) into public function setSection(Section $section).
Perhaps you also need to rename section_title into sectionTitle or simply title, not sure about that.
I'm new in Symfony2. I've a task to create blog. One of the necessary is displaying most popular posts. So I think that the best varient is create listener. It will be call, when visiter will read post. And listener will increment onŠµ of the fild in database(MySQL). I create method in repository, which makes selection by this field. And also create Action, which renders posts by this selection. But when I try to read post, a have error:
FatalErrorException: Error: Call to a member function getId() on a non-object in /var/www/blo/src/Blog/Bundle/BlogBundle/EventListener/PostVisitedListener.php line 20.
Please, help me.
This my Entity (Post):
namespace Blog\Bundle\BlogBundle\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Gedmo\Mapping\Annotation as Gedmo;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* Post
*
* #ORM\Table(name="post")
* #ORM\Entity(repositoryClass="Blog\Bundle\BlogBundle\Entity\PostRepository")
*/
class Post
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="title", type="string", length=255)
* #Assert\NotBlank
* #Assert\Length(min="13", max="255")
*/
private $title;
/**
* #var string
*
* #ORM\Column(name="author", type="string", length=100)
* #Assert\NotBlank
* #Assert\Length(min="13", max="100")
*/
private $author;
/**
* #var string
*
* #ORM\Column(name="post", type="text")
* #Assert\NotBlank
* #Assert\Length(min="100")
*/
private $post;
/**
* #var string
*
* #ORM\Column(name="image", type="string", length=100)
*/
private $image;
/**
* #Gedmo\Timestampable(on="create")
* #ORM\Column(name="createdAt", type="datetime")
*
*/
private $createdAt;
/**
*
* #ORM\Column(name="tags", type="text")
*/
private $tags;
/**
* #ORM\ManyToOne(targetEntity="Category", inversedBy="posts")
*/
private $category;
/**
* #ORM\OneToMany(targetEntity="Comment", mappedBy="post")
*/
private $comments;
/**
* #var integer
*
* #ORM\Column(name="visitedIncrement", type="integer")
*/
private $visitedIncrement;
public function __construct()
{
$this->comments = new ArrayCollection();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set title
*
* #param string $title
* #return Post
*/
public function setTitle($title)
{
$this->title = $title;
return $this;
}
/**
* Get title
*
* #return string
*/
public function getTitle()
{
return $this->title;
}
/**
* Set author
*
* #param string $author
* #return Post
*/
public function setAuthor($author)
{
$this->author = $author;
return $this;
}
/**
* Get author
*
* #return string
*/
public function getAuthor()
{
return $this->author;
}
/**
* Set post
*
* #param string $post
* #return Post
*/
public function setPost($post)
{
$this->post = $post;
return $this;
}
/**
* Get post
*
* #return string
*/
public function getPost()
{
return $this->post;
}
/**
* Set image
*
* #param string $image
* #return Post
*/
public function setImage($image)
{
$this->image = $image;
return $this;
}
/**
* Get image
*
* #return string
*/
public function getImage()
{
return $this->image;
}
/**
* Set tags
*
* #param string $tags
* #return Post
*/
public function setTags($tags)
{
$this->tags = $tags;
return $this;
}
/**
* Get tags
*
* #return string
*/
public function getTags()
{
return $this->tags;
}
/**
* Set category
*
* #param $category
* #return $this
*/
public function setCategory($category)
{
$this->category = $category;
return $this;
}
/**
* Get category
*
* #return integer
*/
public function getCategory()
{
return $this->category;
}
/**
* Set comments
*
* #param string $comments
* #return Post
*/
public function setComments($comments)
{
$this->comments = $comments;
return $this;
}
/**
* Get comments
*
* #return string
*/
public function getComments()
{
return $this->comments;
}
/**
* #param \DateTime $createdAt
*/
public function setCreatedAt($createdAt)
{
$this->createdAt = $createdAt;
return $this;
}
/**
* #return \DateTime
*/
public function getCreatedAt()
{
return $this->createdAt;
}
/**
* #param int $visitedIncrement
*/
public function setVisitedIncrement($visitedIncrement)
{
$this->visitedIncrement = $visitedIncrement;
return $this;
}
/**
* #return int
*/
public function getVisitedIncrement()
{
return $this->visitedIncrement;
}
public function __toString()
{
return $this->getTitle();
}
}
This is my PostRepository
public function visitedIncrement($id)
{
$query = $this->getEntityManager()
->createQuery(
'UPDATE BlogBlogBundle:Post p
SET p.visitedIncrement = p.visitedIncrement + 1
WHERE p.id = :post_id')
->setParameter(':post_id', $id);
$query->execute();
This is my PostVisitedEvent
namespace Blog\Bundle\BlogBundle\Event;
use Blog\Bundle\BlogBundle\Entity\Post;
use Symfony\Component\EventDispatcher\Event;
class PostVisitedEvent extends Event
{
protected $post;
/**
* #param Post $post
*/
public function setPost(Post $post)
{
return $this->post;
}
/**
* #return Post
*/
public function getPost()
{
return $this->post;
}
}
This is my PostVisitedListener
namespace Blog\Bundle\BlogBundle\EventListener;
use Blog\Bundle\BlogBundle\Entity\PostRepository;
use Doctrine\ORM\EntityManager;
use Blog\Bundle\BlogBundle\Event\PostVisitedEvent;
class PostVisitedListener
{
protected $repository;
public function __construct(PostRepository $repository)
{
$this->repository = $repository;
}
public function onPostVisited(PostVisitedEvent $event)
{
$this->repository->visitedIncrement($event->getPost()->getId());
}
This is my Action (it opens post and gives a opportunity to create comment):
public function showPostAction($id)
{
$postRepository = $this->container->get('blog_blog_bundle.post.repository');
$post = $postRepository->find($id);
if (!$post) {
throw $this->createNotFoundException('The post is not found!');
}
$commentRepository = $this->container->get('blog_blog_bundle.comment.repository');
$comments = $commentRepository->findCommentForPost($post->getId());
$event = new PostVisitedEvent();
$event->setPost($post);
$eventDispatcher = $this->get('event_dispatcher');
$eventDispatcher->dispatch('blog_blog_bundle.post_visited', $event);
return $this->render('BlogBlogBundle:Default:showPost.html.twig', array(
'post' => $post,
'comments' => $comments,
));
}
Yuo can see, that I also create services for repositories and listener. There are:
service id="blog_blog_bundle.post.repository" class="Blog\Bundle\BlogBundle\Entity\PostRepository" factory-service="doctrine.orm.entity_manager" factory-method="getRepository"
argument>BlogBlogBundle:Post argument
service
service id="blog_blog_bundle.comment.repository" class="Blog\Bundle\BlogBundle\Entity\CommentRepository" factory-service="doctrine.orm.entity_manager" factory-method="getRepository"
argument BlogBlogBundle:Comment argument
service
service id="blog_blog_bundle.post_visited_listener" class="Blog\Bundle\BlogBundle\EventListener\PostVisitedListener"
argument type="service" id="blog_blog_bundle.post.repository"
tag name="kernel.event_listener" event="blog_blog_bundle.post_visited" method="onPostVisited"
service
Please, help me.
public function onPostVisited(PostVisitedEvent $event)
{
if (!($event->getPost() instanceof PostInterface)) return;
$this->repository->visitedIncrement($event->getPost()->getId());
}
PostInterface is not a symfony interface. You have to code it. Asking for interface is better than asking for a concrete instance because symfony sometimes uses proxy classes instead of concrete classes.