Google News
logo
Phalcon - Interview Questions
What is Dependency Injection in Phalcon?
Phalcon\Di is a container that stores services or components (classes). These services are available throughout the application and ease development. Let us assume we are developing a component called InvoiceComponent that performs some calculations for a customer’s invoice. It requires a database connection to retrieve the Invoice record from the database.
 
Our component can be implemented as follows :
<?php

use Phalcon\Db\Adapter\Mysql;

class InvoiceComponent
{
    public function calculate()
    {
        $connection = new Mysql(
            [
                'host'     => 'localhost',
                'username' => 'root',
                'password' => 'secret',
                'dbname'   => 'tutorial',
            ]
        );
        
        $invoice = $connection->exec(
            'SELECT * FROM Invoices WHERE inv_id = 1'
        );

        // ...
    }
}

$invoice = new InvoiceComponent();
$invoice->calculate();
We use the calculate method to get our data. Inside the method, we create a new database connection to MySQL with set credentials and after that we execute a query. Although this is a perfectly valid implementation, it is impractical and will hinder the maintenance of our application later on, due to the fact that our connection parameters or type of the database are hard coded in the component.
Advertisement