How to access PDO object in class file - Slim 3


#1

Hi Friends,

I am developing sample APIs to learn Slim 3. Now, I got issue to access PDO object to insert data.

routes.php
$app->group('/api', function () {
    $this->group('/v1', function () {
         $this->group('/user', function () {
            new AuthController($this);
        });
         $this->group('/events', function() {
                new EventsController($this);
         });
        

});
});


class AuthController extends Utilities
{
    var $sapp;
    public function __construct($app)
    {
        $this->sapp = new Slim\App();
        $this->sapp = $app;
       
        $app->map(['POST'], '/signin/', [$this, 'signin'])->setName('signin');
        $app->map(['POST'], '/logout/', [$this, 'logout'])->setName('logout');
        $app->map(['POST'], '/signup/', [$this, 'signup'])->setName('signup');
        $app->map(['POST'], '/forgot_password/', [$this, 'forgot_password'])->setName('forgot_password');
    }

    public function signin($request, $response, $args) {
       
    }
    public function logout($request, $response, $args) {
       
    }
    public function signup($request, $response, $args) {
       
        $appuser = new AppUser();
        $appuser->appobject = $this->sapp;
        $allPostPutVars = $request->getParsedBody();
         
        
        
        if(Utilities::HasVariableBlank($allPostPutVars["first_name"]))
            $appuser->first_name = Utilities::$output;
        else
            return $response->withJson(Utilities::ConvertTextToJSON("First Name is missing!!!"), 401);       
        if(Utilities::HasVariableBlank($allPostPutVars["last_name"]))
            $appuser->last_name = Utilities::$output;
        else
            return $response->withJson(Utilities::ConvertTextToJSON("Last Name is missing!!!"), 401); 
        if(Utilities::HasVariableBlank($allPostPutVars["email"]))
            $appuser->email = Utilities::$output;
        else
            return $response->withJson(Utilities::ConvertTextToJSON("Email is missing!!!"), 401);
        if(Utilities::IsValidEmail($allPostPutVars["email"]))
            $appuser->email = Utilities::$output;
        else
            return $response->withJson(Utilities::ConvertTextToJSON("Email is Invalid format"), 401);
        if(Utilities::HasVariableBlank($allPostPutVars["source"])){
            $appuser->source = Utilities::$output;
            if(Utilities::IsValidSource($allPostPutVars["source"]))
                $appuser->email = Utilities::$output;
            else
                return $response->withJson(Utilities::ConvertTextToJSON("Source is Invalid"), 401);
        }
        else
            return $response->withJson(Utilities::ConvertTextToJSON("Source is missing!!!"), 401); 
        if(Utilities::HasVariableBlank($allPostPutVars["phone_number"]))
            $appuser->phone_number = Utilities::$output;
        else
            return $response->withJson(Utilities::ConvertTextToJSON("Phone Number is missing!!!"), 401);
        $appuser->IsEmailExists();
        
        
//GET
        //$allGetVars = $request->getQueryParams();
        //foreach($allGetVars as $key => $param){
           //GET parameters list
        //}

        //POST or PUT
        //$allPostPutVars = $request->getParsedBody();
        //foreach($allPostPutVars as $key => $param){
           //POST or PUT parameters list
        //}
        
        //$getParam = $allGetVars['title'];
        
        
        
        
    }
    public function forgot_password($request, $response, $args) {
       
    }
}
class EventsController
{
}

appuser.php class

<?php
class AppUser extends Utilities{
    
    public $id;
    public $first_name;
    public $last_name;
    public $email;
    public $email_verification_code;
    public $email_verification_date_time;
    public $phone_number;
    public $source;
    public $is_active;
    public $is_delete;
    public $token;
    public $token_expire;
    public $system_date;
    
    public $appobject;
    
    public function __construct(){
        
    }
    
    public function IsEmailExists(){
        
        
        
        $this->appobject->db->prepare("SELECT id FROM sq_app_users WHERE email=:email");
        $sth = $this->appobject->db->prepare($sql);
        $sth->bindParam("email", $email);
        $sth->execute();
        print_r($this->appobject->db);
    }
    public function signup($request){
        
    }
    
}

Here am getting error Undefined property: Slim\App::$db error. Can you please tell me how to access $db ?

Thanks


#2

Instead of $this->appobject->db, try $this->appobject->getContainer()->get('db').

Alternatively, you use the container to take care of constructing the AuthController and AppUser instances including the dependencies. This way the controller becomes simpler and more testable.

Add the definitions to the container:

// define services, including the database, AppUser and controller
$container = [
    'db' => function ($container) {
        return new PDO(/* ... */);
    },
    AppUser::class => function ($container) {
        $db = $container->get('db');

        return new AppUser($db); // add $db as constructor argument to AppUser
    },
    AuthController::class => function($container) {
        $appUser = $container->get(AppUser::class);
        
        return new AuthController($appUser); // add $appUser as constructor argument to  AuthController
    }
];

$app = new \Slim\App($container);

// remove the routes from the controller constructor
$app->map(['POST'], '/signin/', AuthController::class .  ':signIn')->setName('signin');
$app->map(['POST'], '/logout/', AuthController::class . ':logOut')->setName('logout');
$app->map(['POST'], '/signup/', AuthController::class . ':signUp')->setName('signup');
$app->map(['POST'], '/forgot_password/', AuthController::class . ':forgotPassword')->setName('forgot_password');

$app->run();

The AuthController class can then be changed to:

class AuthController
{
    private $appUser;

    public function __construct(AppUser $appUser)
    {
        $this->appUser = $appUser;
    }

    public function signUp($request, $response, $args)
    {
        // use $this->appUser
        // ...
    }
}

#3

Thank you so much. You made my day.