简体   繁体   中英

How to create a new public method in a model?

I am getting started with Laravel 4 and I wish to create a registration functionality.

In this functionality, I want to have a method like

User::is_active()

So I can check in the DB if the confirmation_token is there or not.

In my User model i am creating:

public static function is_active(){
    return empty($this->confirmation_token);
}

Obviously, I can't use $this inside a static method. But how will I use User::is_active() statement?

In your case you should not use a static method. In OOP you want to use static methods when they conceptually don't belong to an instance of something, or when you don't need access to instance members.

Saying that, you should use an instance method (without the static keyword):

public function is_active()
{
    return empty($this->confirmation_token);
}

Then you will call that method doing the following:

$user = User::first(); // or any logic to find a user.
$active = $user->is_active();

The fact that you need access to an instance member: $this->confirmation_token clearly indicates you that you don't need a static method, but an instance method.

Happy coding!

It seems to me like you are looking to set a session. However don't use a token to check the user. If you are using the built in token it will always return true since this is set even for a user who has just come to the website. You will most likely want to set something like username with

 Session::put('username', 'test');

then you can check for a active user with

Session::get('username');

I would suggest looking at http://laravel.com/docs/security this as well since you will most likely want to implement something a little more robust down the rode depending on the information your app will be holding.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM