Can't pass value of parameter into findOneBy Symfony repository - php

I am using Symfony (version 2.5.0-DEV) and the doctrine mongodb cookbook on http://symfony.com/doc/current/bundles/DoctrineMongoDBBundle/index.html.
I am stuck at the moment trying to pass the value of a defined parameter into findOneByIndex.
So if I do the following $script = $repository->findOneByIndex(1); it works perfectly.
But if I do the following $script = $repository->findOneByIndex($user); it fails to search with the value of user.
In routing.yml, I have this pattern: platform/designing/users/{user}/showuser and in the controller I simply do this under the showuserAction:
$repository = $this->get('doctrine_mongodb')->getManager()->getRepository('MyMpBundle:Scripts');
$script = $repository->findOneByIndex($user);
Any help would be appreciated :).

In your last code example, what is the type of the $user variable? I assume it may be a string if it's a routing parameter and coming from the URI. You can use var_dump() to get the type and value in one shot.
Based on an earlier comment, you said that the Scripts document had the following fields:
_id
name (string)
description (string)
index (integer)
user_id (integer)
If the index field in your MongoDB document is an integer, you will need to use an integer in the query. For instance, the findOneByIndex('1') will not match a document with integer 1 in its field. A best practice here is to cast your values to the appropriate type before querying. It may also be best to stop relying on the magic DocumentRepository methods and explicitly define your own findBy methods, which do the casting internally. Then, your controller can pass a numeric string directly from a routing or request parameter and not have to worry about doing the integer cast on its own.
Also, to comment on your original code example:
$script = $repository->findOneByIndex($user);
This was for the routing pattern platform/designing/users/{user}/showuser. You said that this failed to find a result. I assume the $user argument to your controller is a user ID. If that is the case, why were you querying on the index field instead of user_id?

This value should be an integer, not object. Please pass the id, or index value - I don't know how it's stored in mongodb.
$repository = $this->get('doctrine_mongodb')->getManager()->getRepository('MyMpBundle:Scripts');
$script = $repository->findOneByIndex($user->getId());

Do you pass $user to showuser action? like this (notice $user as parameter):
public function showuserAction($user)
{
$repository = $this->get('doctrine_mongodb')->getManager()->getRepository('MyMpBundle:Scripts');
$script = $repository->findOneByIndex($user);
}
PS. I'd recommend you to change var $user to $userId just not to mistake it with $user object

Related

How to access value of a particular post field in symfony 2.8

I want to access a particular field value when posted, similar to $_POST['title'] in core PHP. How can I achieve this in Symfony 2.8?
So far I have tried using
$request->request->get('name') --- returns all values from post.
$request->request->all() --- same returns all values.
$request->request->get($form->get('name')) -- again same..returns all values
If I pass something in get() it shows nulls, eg:- If I passed $request->request->get('Title') --- returns null.
I have attached the image for better understanding.
Returns All
Returns Blank
Controller
You can do like this :
$request->query->get('Title');
// OR
$request->request->get('Title');
// OR
$request->get('Title');
You can also able to this with Entity:
$article = new Article();
$article->getTitle();
Full Information : https://symfony.com/doc/current/introduction/http_fundamentals.html#symfony-request-object
I solved it by storing it into a variable, like this
$data = $request->request->get('form');
//or
$data = $request->request->all();
and then accessing it through array keys. $data['Title'];

Laravel get query string

I have the following url
http://project.su/?invitee=95
first i want to check the invitee in url, if the url have invitee then get the value.
What i have tried (controller) :
if(!empty($request->get('invitee'))){
$user->invitee = $request->get('invitee');
}
The following code is not working .
I want storing the invitee result(id) in database.
Thanks.
To determine if an input value is present:
if ($request->has('invitee')) {
$user->invitee = $request->input('invitee');
}
The has method returns true if the value is present and is not an empty string:
As far as Laravel 5.7 is concerned, the preferred way to retrieve query params is
if( $request->has('invitee') ) {
$request->query('invitee');
}
or using the helper function if you don't have access to $request
request()->query('invitee');
In laravel 5.7, we can also use request()->invitee. By using this, we can get both, URL path parameters and query parameters. Say we have below URL
http://localhost:8000/users/{id}?invitee=95
To read id and invitee, we can use
$id ✔
$invitee ✖ - Invalid
request()->id ✔
request()->invitee ✔
You can get input by:
$invitee = Input::get('invitee');
For above 5.*
$invitee = $request->input('invitee');
Or
$invitee = Request::input('invitee');
To check if invitee parameter exists:
if($request->has('invitee')) {
// ...
}
To get the value of invitee:
$invitee = $request->input('invitee');
Are you calling $user->save() anywhere? You should call $user->save() to actually persist the data.
You can always check by calling dd($user); right after the second line in you example if you are worried it is not set correctly, this way you can see what attributes are set in the $user object.
Also you can replace !empty($request->get('invitee')) with $request->has('invitee').

How does Doctrine populate id property of an Entity after successful insert/persist operation?

Using ORM
$timer = new Timer(); //an object marked as a Doctrine Entity
$this->em->persist($timer);
print $timer->getId(); //blank - not yet set
$this->em->flush($timer);
print $timer->getId(); //prints ID of newly inserted record
Actual ORM Code (Doctrine)
public function persist($entity)
{
if ( ! is_object($entity)) {
throw ORMInvalidArgumentException::invalidObject('EntityManager#persist()' , $entity);
}
$this->errorIfClosed();
$this->unitOfWork->persist($entity);
}
Question
How does Doctrine insert insert_id into the Entity, when the ORM's code above has no "pass by reference" directive?
I.e. normally I'd expect something like this:
public function persist(&$entity)
{
...
}
to indicate that the entity will be modified (with insert_id) during the persist process. But there is nothing of the sort. Nevertheless, Entity is populated with insert_id magically.
How does that happen exactly?
Objects are passed (and assigned) by reference. No need to use address of operator.
One of the key-points of PHP 5 OOP that is often mentioned is that "objects are passed by references by default". This is not completely true. This section rectifies that general thought using some examples.
A PHP reference is an alias, which allows two different variables to write to the same value. As of PHP 5, an object variable doesn't contain the object itself as value anymore. It only contains an object identifier which allows object accessors to find the actual object. When an object is sent by argument, returned or assigned to another variable, the different variables are not aliases: they hold a copy of the identifier, which points to the same object.
PHP documentation
Id set in UnitOfWork::executeInserts.
$postInsertIds = $persister->executeInserts();
if ($postInsertIds) {
// Persister returned post-insert IDs
foreach ($postInsertIds as $postInsertId) {
$id = $postInsertId['generatedId'];
$entity = $postInsertId['entity'];
$oid = spl_object_hash($entity);
$idField = $class->identifier[0];
$class->reflFields[$idField]->setValue($entity, $id);

Passing parameters on redirect with last id saved in Yii

is it possible to pass a parameter to the rediret function ?
I've tried
$this->redirect(array(Yii::app()->request->urlReferrer, 'id' => Yii::app()->db->getLastInsertId());
The id is the last saved id.
On getting lastinsertid, is there a better method, avoiding to query the DB. Isnt a return value from the save command?
Thank you in advance for your help
As you can read in the documents:
public void redirect(mixed $url, boolean $terminate=true, integer $statusCode=302)
$url : the URL to be redirected to. If the parameter is an array, the first
element must be a route to a controller action and the rest are GET
parameters in name-value pairs.
So you could give a string like:
$this->redirect('http://www.google.com');
Or an array():
$this->redirect(array('controller/action' , array('id' => $id , 'anotherParameter' => $id2)) );
I would avoid using getLastInsertId() as it might not always return what you previously have created. If you are using Active Record the ID property of the model will be populated after the save of this model.
So you can simly do:
$redirectId = $model->id;

Getting database values into objects

The thing is that you have classes and then you have the database data. When you create an object how do you set the objects properties to contain the data in the database ?
I saw something like this and I'm wondering if this is really the best way to do it. I'm sure this is a fairly common issue, but I don't know what are the most accepted solutions on how to handle it.
In this example when the object is created you pass an id as a parameter and then you run a query to the database with the id and you assing the returned values to the object properties. I don't have much PHP experience and haven't seen this used much.
Is this an acceptable way to achieve this purpose ? Is there a better or more accepted way ?
public function __construct($id = null){
if($id != null){
$sql = "SELECT *
FROM users
WHERE user_id = $id";
$res = Db::returnRow($sql);
// $res contains an associative array with database columns and values
if($res){
$this->user_id = $res['user_id'];
$this->user_name = $res['user_name'];
//and so on...
}
}
}
Could somebody provide some sample code or pseudocode to illustrate what is the correct way to do this ?
It could be an acceptable way for a homework maybe. But architecturaly it is not.
Your class that is representing your business data (a user in your example) must be loosely coupled with your database access logic. In the end the PHP class acting as a user should not be aware that the data come from a database, a file or any other resource. Following that you will be able to reuse your user php class in other projects without having to change anything to it! If you have your data access logic inside it you are stuck.
Conclusion: I would suggest to read some resources on Design Pattern (in your situation take a look at DAO pattern) ;) Hint: the one from Head First series is extremely accessible and enjoyable.
You could create a function to do this for you automatically, by looping over the associative array's key/value pairs. Or you could look into using an ORM library.
Yes, you can semi-automate this by having a parent class all objects inherit from. On load, it queries, "SHOW FIELDS FROM [my tablename]" and populates an associative array with the names. If an id has been passed in, it looks for a valid object in that table with that id and assigns the values to the array.
Side note: don't pass your id directly into your query like that. Parametize the sql and wrap a function around any user input to sanitize it.
If it's mysql, you can just do:
$obj = mysql_fetch_object($query);
PDO the ability to use arbitrary classes as the target for a fetch, but beware that they assign the variable data before running the constructor:
$pdo->query($stmt, PDO::FETCH_CLASS, "MyClass", array('foo'=>'bar'));
...where the final parameter contains arguments for your class constructor.

Categories