anandkunal / ToroPHP

Toro is a PHP router for developing RESTful web applications and APIs.
http://toroweb.org
MIT License
1.17k stars 173 forks source link

ToroPHP and dependency injection #90

Open Ecaz opened 10 years ago

Ecaz commented 10 years ago

Hello! I just picked up ToroPHP and I normally use DI when I do any kind of database interaction.

Rough example

$db = new PDO("mysql:host=myhost;dbname=myname", "username", "password");
$object = new Object($db);

class Object {
    private $db;

    function __construct($dbConn) {
        $this->db = $dbConn;
    }

    function get($string) {
        $sql = $this->db->prepare("statement GOES here");
    }
}

But ToroPHP doesn't allow you to do this, is there any way to get around this? I don't wanna use a global variable.

Toro::serve(array(
    "/" => "Object",
    "/get/:string" => "Object" //would be injected somewhere so you could get :string from the db.
));
rmrhz commented 10 years ago

Question, in what kind of implementation are you trying to achieve?

Ecaz commented 10 years ago

What do you mean? The project I'm working on right now would get data from a database based on the get request. So if they browse to /get/port/12345 they would get port info for user 12345. Except it's an API so they wouldn't browse to it

And I might add that I'm not a fan of singleton.

VeeeneX commented 10 years ago

This is how Toro serve handler:

   $result = call_user_func_array(array($handler_instance, $request_method), $regex_matches);

So if you change it to something like this:

   $result = call_user_func_array(array($handler_instance, $regex_matches[1]), array($regex_matches[2]));

And define it like /{controller}/{action}/{params} This might work.