Database instance in RouterFactory

4 years ago

ivopisarovic
Member | 5
+
0
-

Hello,
is it possible to get a link to the database instance in RouterFactory? I have tried it in the FILTER callback and also creating own route, but always: “Call to a member function table() on a non-object”. Bootstrap is standard from Nette 2.2.1 sandbox. DB connection set in config.local.neon.
Thanks for help.

class PageRoute extends \Nette\Application\Routers\Route{

    /** @var \Nette\Database\Context */
    protected $db;

    public function match(HttpRequest $request){
        $id = $request->getQuery('id');
        if(!is_numeric($id)){
            $page = $this->db->table('menu')->where('url', $id)->fetch();
            if($page == NULL){
                return NULL;
            }
      ... following code....

Last edited by ivopisarovic (2014-09-25 18:56)

4 years ago

Quinix
Member | 108
+
+1
-

You have to inject it to RouteFactory and pass it to your custom route manually:

<?php

namespace App;

class RouterFactory
{
    private $connection;

    function __construct(\Nette\Database\Context $connection)
    {
        $this->connection= $connection;
    }

    public function createRouter()
    {
        $router = new RouteList();

        $router[] = new PageRoute($this->connection);
        ///...

        return $router;
    }
}
?>

4 years ago

Jan Tvrdík
Nette guru | 2547
+
+1
-

Because PageRoute is subclass of Route, setter injection is most likely preferred.

4 years ago

ivopisarovic
Member | 5
+
0
-

Super, that's it. Thank you!

3 years ago

ic
Member | 413
+
0
-

Quinix wrote:

You have to inject it to RouteFactory and pass it to your custom route manually:

<?php

namespace App;

class RouterFactory
{
    private $connection;

    function __construct(\Nette\Database\Context $connection)
    {
        $this->connection= $connection;
    }

    public function createRouter()
    {
        $router = new RouteList();

        $router[] = new PageRoute($this->connection);
      ///...

        return $router;
    }
}
?>

If I try this one… it says ‘Using $this when not in object context’.