I'm trying to get an item from the database and pass it to a new item to push to the database.
$post = $entityManager->getRepository('App:Post')
->find($id);
$comment->setPost($post)
the setPost looks like the following:
public function setPost(Post $post): self
{
$this->post = $post;
return $this;
}
and the $post variable:
/**
* #ORM\ManyToOne(targetEntity="App\Entity\Post", inversedBy="comments")
* #ORM\JoinColumn(nullable=false)
*/
private $post;
But when i try to set the post like setPost($post) it gives me the following error:
Expected parameter of type '\App\Entity\Post', 'object' provided
I assume, that the error you see is from your integrated developent environment (IDE), for example eclipse, vs code, phpstorm, and others. But the code - when actually executed - should work.
Now, the error most likely stems from a static code analysis running in the background of said IDE, which will look at the statement and trying to analyze according to the called methods, accessed properties etc. of which type your variables are.
So, let's do this slowly (and you can probably hover over the $vars and ->methods() do verify. The line I'm interested in is
$post = $entityManager->getRepository('App:Post')
->find($id);
so $entityManager is of type EntityManagerInterface, which has a getRepository method with one required parameter of type string ('App:Post' in your case), and it will return an object of type ObjectRepository, which has a method find which requires one parameter (mixed, don't ask), and returns ?object which means, an object or null. So, $post is of type object (best case, or null, in which case it would fail!). Now, the next line obviously expects a parameter of type Post and not of type object, thus the warning/notice/error.
Now, static code analysis is quite helpful up to a certain level, but it isn't infallible because it has limitations. It doesn't know what runtime will actually return, it just assumes that the type hints found in the code (of doctrine) are sufficiently specific - which they aren't in your case.
the easy fix
add a doc string to tell static code analysis what the variable $post's type actually is:
/** #var Post $post */
$post = $entityManager->getRepository('App:Post')
->find($id);
this explicitly tells the static analysis tool, that $post is of type Post, maybe you have to write App\Entity\Post or even \App\Entity\Post.
the hard fix
Alternatively, you could implement your own PostRepository (doctrine provides some help) and define a function like function findById($id) :Post - which would explicitly tell static code analysis, what the return type is when you call it in your code (injected in your function via dependency injection: PostRepostory $postRepository):
$post = $postRepository->findById($id);
If you're using lots and lots of different entities, this is a very verbose solution but depending on your project it might be worth it, since you explicitly name the dependencies instead of injecting the very unspecific (as we have seen) EntityManagerInterface. Using the EntityManagerInterface might make testing HELL (imho!).
Related
I have a question: I need to get communication with algolia, but i cannot get that work, since of leak of documentation. I have symfony 5.4 but algora docs provide only for version 4, second when I trying to get some of my entities indexed i get stuck at the point when i have to provide entityManager which suppose to implement ObjectManager, but that one it is not wired in the service. And how many people suggest we should not use this directly and use EntityManagerInteface instead. So how i have to index my Entity?
What i did:
composer require algolia/search-bundle
Added credentials:
ALGOLIA_APP_ID="U1RFIHY01W"
ALGOLIA_API_KEY="YourAPIKey"
Trying to index in the controller for testing:
public function searchPosts(Post $post, ManagerRegistry $em): JsonResponse
{
$posts = $this->postRepository->searchPosts('82819');
$postsArray = [];
/**#var Post $post */
foreach ($posts as $post){
$postsArray = $post->normalize();
}
$this->searchService->index($em->getManager(), $postsArray);
return new JsonResponse($this->searchService->getConfiguration());
}
Right now since i use ManagerRegestry i get an error:
get_class(): Argument #1 ($object) must be of type object, int given
Can you help me work around? Thank you
Separate the two instructions with :
$entityManager= $em->getManager();
and then
$this->searchService->index($entityManager, $lpostsArray);
I was going through some code in symfony, and I found
$request->request->replace()
Actually, a form is posted and its value is fetched in a function say,
public function someFunction(Request $request){
$data = $request->request->all() ? : json_decode($request->getContent(), true);
$request->request->replace($data);
}
When I dumped,
$request->request->replace($data)
The result is null. I didn't understand why is it used and what are its benefits?
I searched about it, some say it is used to sanitise the data, some say we should not use it as replaces all of the parameters in the request instead we should use set method.
And I did not get any of it as I am new to symfony.
What does $request->request->replace() does with the parameter provided to it?
Your $request is an instance of Symfony\Component\HttpFoundation\Request
. Using $request you have access to properties such as request, query, cookies, attributes, files, server, headers. Each of these properties is of type Symfony\Component\HttpFoundation\ParameterBag. Instance of ParameterBag provides access to request parameters using method $request->request->all(). This method will return 'parameters' property of ParameterBag instance.
The $request->request->replace($data) will set 'parameters' property in ParameterBag instance to $data.
Also replace() method does not have any return type that's why when you dumped $request->request->replace($data) you got null as output.
If you want to add some extra parameters to your request then replace() is not the right choice rather you should use set() method in ParameterBag.
I want to create a settings page, which only has a form in it. If the form is submitted it only updates settings entity but never creates another one. Currently, I achieved this like:
/**
* #param SettingsRepository $settingsRepository
* #return Settings
*/
public function getEntity(SettingsRepository $settingsRepository): Settings
{
$settings = $settingsRepository->find(1);
if($settings == null)
{
$settings = new Settings();
}
return $settings;
}
In SettingsController I call getEntity() method which returns new Settings entity (if the setting were not set yet) or already existing Settings entity (if setting were set at least once).
However my solution is quite ugly and it has hardcoded entity id "1", so I'm looking for a better solution.
Settings controller:
public function index(
Request $request,
SettingsRepository $settingsRepository,
FlashBagInterface $flashBag,
TranslatorInterface $translator,
SettingsService $settingsService
): Response
{
// getEntity() method above
$settings = $settingsService->getEntity($settingsRepository);
$settingsForm = $this->createForm(SettingsType::class, $settings);
$settingsForm->handleRequest($request);
if ($settingsForm->isSubmitted() && $settingsForm->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($settings);
$em->flush();
return $this->redirectToRoute('app_admin_settings_index');
}
return $this->render(
'admin/settings/index.html.twig',
[
'settings_form' => $settingsForm->createView(),
]
);
}
You could use Doctrine Embeddables here.
Settings, strictly speaking, should not be mapped to entities, since they are not identifiable, nor meant to be. That is, of course, a matter of debate. Really, a Settings object is more of a value object than an entity. Read here for more info.
So, in cases like these better than having a one to one relationship and all that fuzz, you probably will be fine with a simple Value Object called settings, that will be mapped to the database as a Doctrine Embeddable.
You can make this object a singleton by creating instances of it only in factory methods, making the constructor private, preventing cloning and all that. Usually, it is enough only making it immutable, meaning, no behavior can alter it's state. If you need to mutate it, then the method responsible for that should create a new instance of it.
You can have a a method like this Settings::createFromArray() and antoher called Settings::createDefaults() that you will use when you new up an entity: always default config.
Then, the setSettings method on your entity receieves only a settings object as an argument.
If you don't like inmutablity, you can also make setter methods for the Settings object.
I find it somewhat annoying to have to constantly use #var on getUser. It seems sloppy.
So I was thinking about starting to use this instead
<?php
// in the controller
$user = Customer::isCustomer($this->getUser());
// in the entity
/**
* #param Customer $user
*
* #return Customer
*/
public static function isCustomer(Customer $user)
{
return $user;
}
Is this a good idea? Bad idea? Horrible idea?
A type hint is the better option in this case.
Why would you write more code by adding checks manually rather than adding a simple type hint to your param.
Your four lines of codes representing two conditions give exactly the same result as:
/**
* #param Customer|null $user
*
* #return Customer|null
*/
public static function isCustomer(Customer $user = null)
{
// If $user is null, it works
// If $user is a Customer instance, it works
// If it's other, an exception is thrown
return $user;
}
Type hinting optimises and give more readability to a code.
It's a convention in symfony2, php and more.
It's commonly used as a constraint (or contract) with you and your method.
Also, it's the only alternative for an interface or an abstract class to add requirement to a parameter, because they don't have a body, and so cannot write conditions.
Update
In SensioLabs Insight, Object type hinting represents a warning using the following message :
The parameter user, which is an object, should be typehinted.
Because the verb should is used, I consider it's not a mandatory requirement, just a very good practice in case of it doesn't cause any problem.
Also, you can use the example you given without making your code horrible.
I want to return a value from entity to view file. Below is my entity function
public function getVisitorName($id)
{
$repository = $this->getDoctrine()->getRepository('SystemVmsBundle:VisitorsDetails');
$product = $repository->findOneBy(array('id' =>$id));
$name=$product->getFirstname();
return $name;
}
This is the line in my view file which calls that function
{{ entity.visitorName(entity.visitorId) }}
Its not giving me any error. But only a blank page. How can i fix this?
This is my controller code
public function indexAction()
{
$em = $this->getDoctrine()->getManager();
$entities = $em->getRepository('SystemVmsBundle:EntryDetails')->findAll();
return array(
'entities' => $entities,
);
}
I am trying to fetch the visitors name(from visitors table) corresponding to the visitor id(in entry table).How will i do it then?
you have two ways of doing it:
1) Map your SystemVmsBundle:EntryDetails entity, to SystemVmsBundle:VisitorsDetails as OntToOne by adding field details to your EntryDetails; , and then in twig template just call it via
{{ entity.details.name }}
2) instead of creating getVisitorName(), it is better to create twig function for this, with same functionality.
Your indexAction() is not returning a response object, it is just returning an array of entities. Controller actions should return a Response containing the html to be displayed (unless they are for e.g. ajax calls from javascript). If you are using twig templates you can use the controller render() method to create your response, something like this:
return $this->render('<YourBundle>:<YourViewsFolder>:<YourView>.html.twig', array(
'entities' => $entities,
));
When you've corrected that I suspect you'll get an error because $this->getDoctrine() won't work from an entity class. The code you have in the getVisitorName() method just shouldn't be in an entity class.
As #pomaxa has already suggested, I believe there should be a relationship between your EntryDetails and VisitorsDetails entities although I don't know enough about your data from the question to know what type of relationship it should be (OneToOne / ManyToOne). If your EntryDetails entity had a relationship to VisitorsDetails, the EntryDetails class would then contain a $visitorsDetails attribute and methods to get/set it. Then the line in your twig file would look like this:
{{ entity.visitorsDetails.firstName }}
There is a section on Entity Relationships / Associations in the Symfony Manual.
Also, I hope you don't mind me giving you a little advice:
Be careful when you copy and paste code as it appears you have done in getVisitorName(). You have kept the variable name '$product' although there are no products in your system. This sort of thing can cause bugs and make the code more difficult to maintain.
I recommend you avoid tacking 'Details' onto the end of entity names unless you genuinely have two separate and related entities such as Visitor + VisitorDetails and a good reason for doing so. I think the entities in your example are actually 'Visitor' and 'VistorEntry'.
Unless you are writing a re-usable component, I recommend you use specific variable names like '$visitorEntries' rather than '$entities' in your controller and twig.
In general, the more meaningful your variable names, the more readable, maintainable and bug-free your code is likely to be. Subsequently, it will also be much easier for people on SO to understand your code and give you help when you need it.