我尝试使用php slim在控制器中访问我的任务模型但是我遇到了这个错误
Too few arguments to function App\Models\Task::__construct(), 0 passed on line 26 and exactly one on TodoController.php
有什么建议吗?在此先感谢,我引用了类似的问题like this,但我无法将其与我所拥有的相关联。
最终我想从Task.php模型中提取方法,并在需要时在控制器中调用它。
TodoController.php
<?php
namespace App\Controllers;
use Slim\Http\Request;
use Slim\Http\Response;
use App\Models\Task;
class TodosController extends BaseController
{
// public function getTodos($request, $response, $args)
// {
// $sth = $this->db->prepare("SELECT * FROM tasks ORDER BY task");
// $sth->execute();
// $todos = $sth->fetchAll();
// return $this->c->view->render($response, 'todos.twig', ['todos' => $todos]);
// }
public function index()
{
$tasks = new Task();
$tasks->getTodos();
}
public function deleteTodo($request, $response, $args)
{
$sth = $this->db->prepare("DELETE FROM tasks WHERE id=:id");
$sth->bindParam("id", $args['id']);
$sth->execute();
$todos = $sth->fetchObject();
$url = urlFor($todos);
var_dump($url);
return $this->response->withJson($todos)->withRedirect('/todos');
}
如果这对我有帮助,那就是我的Task.php
<?php
namespace App\Models;
use Slim\Views\Twig as View;
use Interop\Container\ContainerInterface;
class Task
{
protected $c;
public $db;
public function __construct(ContainerInterface $container)
{
$this->c = $container;
$this->db = $container['db'];
}
public function getTodos($request, $response, $args)
{
$sth = $this->db->prepare("SELECT * FROM tasks ORDER BY task");
$sth->execute();
$todos = $sth->fetchAll();
return $this->c->view->render($response, 'todos.twig', ['todos' => $todos]);
}
}
我还查看了另一个类似的例子like this,但仍然无法理解我做错了什么。
答案 0 :(得分:0)
public function index($req, $res, $args)
{
$tasks = new Task($this->container);
$tasks->getTodos($req, $res, $args);
}