Multi-tendancy, make possible to manipulate data in before events
Hi,
So far I am very happy with the implementation. Its clean and works like it should be, so first of all my credits to you for you work!
I was interested if it is possible to make the data for the insert can be manipulated before insert to the database. In my situation I have a multi-tendant application. I would like to add by default the tendant id for the loggedin user. I am aware the work around is using the after insert and add the tendant id. But we should be aware to not use to much queries to the database. So bring it together in one should be very nice.
Any idea if it is possible and otherwise what I can change to pass the data as reference. I changed in my version already that I have by default the table where the query goes to passed to the event.
Kind regards
Hi @usmanhalalit,
I have made a fix for this to use the data collection where I can make mutations in the before-insert/before-update. If you are interested in the solution, let me know, in that case I will make a pull request.
I was going to suggest the before-insert event, however it looks like the insert data does not get passed to the event, so I suppose this would require a code change. Seems like the insert data should be available during the before-insert event, and be able to be mutated.
// This doesn't work, but it would be nice.
QB::registerEvent('before-insert', 'users', function(&$data)
{
$data['user_id'] = User::getCurrentUserId();
});
*multi-tenancy
Hi @dustingraham, thats correct, I had to change a little bit more. The problem is that the func_get_args() is a reference by itself but get lost from the real reference. So what you have to do is changing the way it works now. I made the change by always push a array with optional information to the events. Each key is linked as reference.
The arguments of my events is changed to this:
QB::registerEvent('before-select', ':any', function($qb, $table, &$args)
What I already said, if people are interested in this solution I will make a push. Let me know in that case.
I think that sounds cool, but depends on @usmanhalalit whether he thinks it would be good to pull in.
I will make a fork and make my changes, after that I will do a pull request.
@dustingraham (CC @usmanhalalit ) I have made a pull request for the behaviour.
Usage is very simple:
QB::registerEvent('before-insert', ':any', function($qb, $table, &$args)
$args["data"]["column"] = have_an_id_to_set; //data key is the value which contains the data which will be insert