Working with Database
Ecotone allows to work with Database using DbalBusinessMethod. The goal is to create abstraction which significantly reduce the amount of boilerplate code required to implement data access layers. Thanks to Dbal based Business Methods we are able to avoid writing integration and transformation level code and focus on the Business part of the system. To make use of Dbal based Business Method, install Dbal Module first.
Write Business Methods
Let's consider scenario where we want to store new record in Persons table. To make it happen just like with Business Method we will create an Interface, yet this time we will mark it with DbalBusinessMethod.
The first parameter passed to DbalBusinessMethod is actual SQL, where we can provide set of named parameters. Ecotone will automatically bind parameters from method declaration to SQL ones by names.
Above example will use DbalConnectionFactory::class for database Connection, which is the default for Dbal Module. If you want to run Business Method on different connection, you can do it using connectionReferenceName parameter inside the Attribute.
Custom Parameter Name
We may bind parameter name explicitly by using DbalParameter attribute.
This can be used when we want to decouple interface parameter names from binded parameters or when name in database column is not explicit enough for being part of interface.
Returning number of records changed
If we want to return amount of the records that have been changed, we can add int type hint to our Business Method:
Query Business Methods
We may want to fetch data from the database and for this we will be using DbalQueryBusinessMethod.
The above will return result as associative array with the columns provided in SELECT statement.
Fetching Mode
To format result differently we may use different fetch modes. The default fetch Mode is associative array.
First Column Fetch Mode
This will extract the first column from each row, which allows us to return array of person Ids directly.
First Column of first row Mode
To get single variable out of Result Set we can use First Column of first row Mode.
This way we can provide simple interfaces for things Aggregate SQLs, like SUM or COUNT.
First Row Mode
To fetch first Row of given Result Set, we can use First Row Mode.
This will return array containing person_id and name.
Returning Nulls
When using First Row Mode, we may end up having no returned row at all. In this situation Dbal will return false, however if Return Type will be nullable, then Ecotone will convert false to null.
Returning Iterator
For big result set we may want to avoid fetching everything at once, as it may consume a lot of memory. In those situations we may use Iterator Fetch Mode, to fetch one by one.
Parameter Types
Each parameter may have different type and Ecotone will try to recognize specific type and set it up accordingly. If we want, we can take over and define the type explicitly.
Last updated