We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Events when performing a SELECT. Does something like "beforeSelect" exist?

Hey guys, I was wondering if Models have something similar to beforeSave that would allow me to modify a select query? Something that would be called "beforeSelect" if it existed.

Why I'd need that? I'm working on a multi-user application and I want to diminish the risks of an user seeing other users data because of a mistake in code. So in every query I need to set the user_id. I'm looking for a way to do that automatically for every query! So I would intercept the query and inject the right user_id.

Do you have suggestions to accomplish that?



2.0k

Can't you select the user by simply doing findFirst(id)? I don't get how other users would be able to get data of someone else, but if you really need that then you can create new model, set the id and then find? which essentialy does the same as findFirst(id).

Having method beforeSelect in the model would just give you always the same user btw since it would be set before every single select of user?.



32.2k

I want to minimize the chance of coding errors. For example:

Select * from clients where id = 23 and user_id = 2;

If I create a function that does that I'm good to go, but I'm using models and it's easy to just do Clients::findFirst(23) and forget to set the user_id. It happend to me a couple times. So I'm stupid and I was wondering if I could automatically set it for all the queries using events.



32.2k

The user_id would be the id of the user currently logged in. So it wouldn't be hard coded like you imagined.



2.0k
edited Oct '14

Sorry, to me it just seems like you are approaching the user login system a bit wrong but thats not the point, if you want query that does what you said above then read properly this section: https://docs.phalcon.io/en/latest/reference/models.html#finding-records

$robots = Clients::find(array(
    "conditions" => "id = ?1 AND user_id = ?2",
    "bind" => array(
        1 => $id,
        2 => $user_id
    )
));

alternatively you can use phql to do query like that: https://docs.phalcon.io/en/latest/reference/phql.html#conditions

$phql = "SELECT * FROM Clients WHERE Clients.id = 23 AND Clients.user_id = 2";
$clients = $manager->executeQuery($phql);