Как передать внутренние методы как метод объекта Redbean PHP - PullRequest
3 голосов
/ 04 июня 2019

Я строю эту новую систему, поэтому я решил, что я улучшу базовый код, который у меня уже был на курсе, который я взял.

Итак, я начал использовать Redbean PHP ORM и теперь столкнулся с некоторыми проблемами.

Я пытаюсь вызвать метод RememberLogin () моего класса User внутри класса Authentication, который до того, как я добавил Readbean, работал нормально, но мне приходилось каждый раз выполнять запрос и т. Д.

Моя проблема в том, что метод RememberLogin () недоступен для меня, где я хочу его вызвать, потому что, по крайней мере, я думаю, что по этой причине у меня теперь есть объект RedBeanPHP \ OODBBean, который возвращает мне все свойства от пользователя, но не методы, есть ли способ сделать это? Или каким-то другим способом достичь той же цели?

\ Controller \ Логин

<?php
namespace App\Controllers\Admin;

use \Core\View;
use \App\Models\User;
use App\Authentication as Auth;
use \App\Flash;

/**
 * Login controller
 */
class Login extends \Core\Controller{

    /**
     * Show the login page
     * 
     * @return void
     */
    public function newAction(){
        View::renderTemplate('Admin/Login/index.html');
    }

    /**
     * Log in a user
     * 
     * @return void
     */
    public function createAction(){
        $user = User::authenticate($_POST['email'], $_POST['password']);

        $remember_me = isset($_POST['remember_me']);

        if($user){
            // Now I can pass the User object as a parameter and access 
            // it's properties, but I still can't access the methods 
            // of the User class
            Auth::login($user, $remember_me);

            // Flash::addMessage(false, 'Login successful');

            // $this->redirect(Auth::getReturnToPage());
        }else{
            Flash::addMessage('Login unsuccessful, please try again', Flash::WARNING);

            View::renderTemplate('Admin/Login/index.html', [
                'email' => $_POST['email'],
                'remember_me' => $remember_me
            ]);
        }
    }
}

\ Model \ User

<?php
namespace App\Models;

use PDO;
use App\Token;
use App\Mail;
use Core\View;
use RedBeanPHP\R;
use Core\Conn\Read;

/**
 * User model
 */
class User{

    /**
     * Error messages
     * 
     * @var array
     */
    public $errors = [];

    private static $User;

    // Table's name
    const Entity = 'users';

    /**
     * Class constructor
     *
     * @param array $data Initial property values
     * 
     * @return void
     */
    public function __construct($data = []){
        foreach($data as $key => $value){
            $this->$key = $value;
        }
    }

    /**
      * Find a user model by email address
      * 
      * @param string $email email address to search for
      * 
      * @return midex User object if found, false otherwise
      */
      public static function findByEmail($email){
          $findByEmail = R::findOne(self::Entity, 'email = :email', [':email' => $email]);

         return $findByEmail;
         // This returns a RedBeanPHP\OODBBean Object
         // Hence why I can't access the methods of the User class
    }

    /**
     * Authenticate a user bu email and password.
     * 
     * @param string $email email address
     * @param string $password password
     * 
     * @return midex The user object or false if authentication fails
     */
    public static function authenticate($email, $password){
        $user = static::findByEmail($email);

        // Right now I have the RedBeanPHP\OODBBean Object and
        // I can access the User properties like "is_active"

        if($user && $user->is_active){
            if(password_verify($password, $user->password_hash)){
                return $user;
            }
        }

        return false;
    }

    /**
     * Remember the login by inserting a new unique token into the remembered_logins table
     * for this user record
     * 
     * @return boolean True if the login was remembered successfully, false otherwise
     */
    public function rememberLogin(){    
        $token = new Token();
        $hashed_token = $token->getHash();
        $this->remember_token = $token->getValue();

        $this->expiry_timestamp = time() + 60 * 60 * 24 * 30;  // 30 days from now

        $remembered_logins = R::xdispense('remembered_logins');
        $remembered_logins->token_hash = $hashed_token;
        $remembered_logins->user_id = $this->id;
        $remembered_logins->expires_at = date('Y-m-d H:i:s', $this->expiry_timestamp);

        $login = R::store($remembered_logins);

        return $login;
    }
}

Authentication.php

<?php
namespace App;

use App\Models\User;
use App\Models\RememberedLogin;
use RedBeanPHP\R;

/**
 * Authentication
 */
class Authentication{

    /**
     * Login the user
     *
     * @param User $user The user model
     *
     * @return void
     */
    public static function login($user, $remember_me){
        session_regenerate_id(true);

        $_SESSION['user_id'] = $user->id;

        if ($remember_me) {
            // Right now I should be able to access the method rememberLogin() of the class User, BUT I STILL CAN'T
            if($user->rememberLogin()){
                setcookie('remember_me', $user->remember_token, $user->expiry_timestamp, '/');
            }
        }
    }
}

Я добавил класс и методы, которые я упомянул в задаче, если вам нужно что-то еще, просто дайте мне знать. Я надеюсь, что проблема ясна

...