PHP MVC: use router inside controller?

I am creating my own MVC framework (to improve my PHP), but I don't know how to deal with best practices.

In my router, I have a method of creating a link using the route name and parameters (the method returns a well-formatted URL), so in my controllers I can use something like:

//inside an action of any of my controllers
$router = Router::getInstance(); //the router is a Singleton
$url = $router->createUrl('articleReadOne', array(65, 'matrix')); //$url = "article/read/65-matrix"
$this->redirectTo($url);

Or inside my views:

//inside a view
<?php $router = Router::getInstance(); ?> 
<a href="<?php echo $router->createUrl('article-read', array(65, 'matrix')); ?>"> Click me </a>

But I can read across the net that using Singleton is bad practice (even for a database class).

I really need to have access to my createUrl () method from inside my controller and from inside my views, but if I don't use the Singleton Router class, how can I β€œinject” my router into my controllers and be able to use it? Is it really bad to use Singleton in this case?

Thank you for your help.

+4
source share
1 answer

A few things:

, . URL/ . , - . , createUrl() , .

, . , (, , ), ( , -, ), , .

, , - , , . , , , , . , . - :

class User {

    private $dbh;

    __construct($dbh) {
        $this->dbh = $dbh;
    }

}

$user = new User($dbh);

, , .

, . , !

+2

Source: https://habr.com/ru/post/1611180/


All Articles