Hi, i have a problem usind the DB connection from a model, i don’t understand, but the same method works fine from a controller. I try to use a container for this…
My explanation is longer so I share a link where you can see code.
Thank you!
Hi, i have a problem usind the DB connection from a model, i don’t understand, but the same method works fine from a controller. I try to use a container for this…
My explanation is longer so I share a link where you can see code.
Thank you!
First off, all of us will strongly disadvice you an injection of a container iny any case, but because it is a pet project, let’s see what you can start with.
As far as I can see:
class ApplicantStatus extends BaseModel{
public function __construct($id)
{
if(isset($id)){
$this->id = $id;
}
}
...
}
extends:
class BaseModel{
protected $container;
public function __construct(ContainerInterface $c){
$this->container = $c;
}
}
so you miss:
parent::__construct($c);
within your constructor declaration of AplicantStatus. As for a code try for a start with this:
class ApplicantStatus extends BaseModel
{
private $id;
public function __construct(ContainerInterface $c, int $id = null)
{
parent::__construct($c);
$this->id = $id
}
...
}
But once again. Do not do it this way. Instead, inject required object instances by the proper way, through your constructors. Try to find some free time to read about strict types in php in relation to dependency injection.
Hi thank you so much.
You’re absolutely right, i was just trying to do something fast with Slim.
But, in the controller, when i consume the connection to the database, in the Controller i don’t use the parent :: and it works.
BaseController.php
namespace App\Controllers;
use Psr\Container\ContainerInterface;
class BaseController{
protected $container;
public function __construct(ContainerInterface $c){
$this->container = $c;
}
}
ApplicantController.php
namespace App\Controllers;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use App\Controllers\BaseController;
use App\Models\ApplicantStatusModel;
use \DateTime;
class ApplicantsController extends BaseController{
public function getAll(Request $request, Response $response, $arg){
//get container db
$pdo = $this->container->get('db');
From:
Note : Parent constructors are not called implicitly if the child class defines a constructor. In order to run a parent constructor, a call to parent::__construct() within the child constructor is required. If the child does not define a constructor then it may be inherited from the parent class just like a normal class method (if it was not declared as private).
Your ApplicantsController does not have any constructor, so its parent’s (BaseController) constructor is called implicitly. Unfortunately this is not a case of ApplicantStatus that possess its own constructor.
You’re right, i missed it. Thank you very much for all the clarifications.