how to use a static method

55 views
Skip to first unread message

v.

unread,
Jun 26, 2019, 5:08:54 AM6/26/19
to Fat-Free Framework
Hi,

I have a method in a model class that checks if a certain user has access to a certain item.
    public function hasAccess($id, $user_id)
   
{
        $this
->load(array('id=? AND user_id=?',$id, $user_id));    
       
if(! $this->dry())
       
{
           
return true;
       
}
       
return false;
   
}

I want to make this method static so I can use it without instantiating the class, using the double colon operator with the impossible name.
This returns an error: Using $this when not in object context
I understand why this is thrown, but I do not know how to solve this while using the ORM functionality of the DB\SQL\Mapper class.
Is there an easy way to get around this or would it make more sense to just instantiate the class first and use the method non-statically?

richgoldmd

unread,
Jun 26, 2019, 5:36:54 AM6/26/19
to f3-fra...@googlegroups.com
You could do this:

public static function hasAccess($id, $user_id) {
    $model
= new self();
    $model
->load(array('id=? AND user_id=?',$id, $user_id));
   
return !$model->dry();
}


You still need an instance of the class, but this hides the details. I also folded your return logic into a single statement. 

v.

unread,
Jun 26, 2019, 5:57:05 AM6/26/19
to Fat-Free Framework
Thanks doc, you put me on the right track.
I need to pass the database instance for it to work (the class extends the db mapper class), but it does the trick:
public static function hasAccess($db, $id, $user_id) {
    $model
= new self($db);

richgoldmd

unread,
Jun 26, 2019, 7:36:22 AM6/26/19
to Fat-Free Framework
👍

ikkez

unread,
Jul 2, 2019, 6:57:51 PM7/2/19
to Fat-Free Framework
just be sure to not use this method too often, as you will make a new user object and the same database queries all the time over and over again.. I'd suggest to instantiate the model once, load the user (active user?!) and put that model into the f3 hive, like

$f3->set('ACTIVE_USER', $user);

and from there on, you can of cause use that object everywhere and dont need a static function.

bcosca

unread,
Jul 2, 2019, 7:29:25 PM7/2/19
to Fat-Free Framework
Here's a shorter way of writing it:

public static function hasAccess($id, $user_id) {
    $model 
= new self();
    return !!$model
->load(array('id=? AND user_id=?',$id, $user_id)); 
}


Reply all
Reply to author
Forward
0 new messages