Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

Accessing the database from a view using Volt

I have been told that Volt can request data from the database inside the view file but have not found any code demonstrating this. Could someone provide an example of a database request through Volt? Also, can Volt alter the data in the database, i.e. rather than just requesting data it can also send all other sorts of database requests (insert/update/delete...) too?



35.7k
Accepted
answer
edited Aug '15

The purpose of the MVC pattern is to separate models, views and controllers into easily manageable blocks. Accessing the database directly from a view seriously violates that idea.

That being said, you may use the database connection service:

// some/view.volt
{{ set rows = db.fetchAll("SELECT * FROM tbl") }}

{{ db.execute("INSERT INTO tbl (col) VALUES ('val')") }}

{{ set statement = db.prepare("UPDATE tbl SET col=?") }}
{{ statement.execute(['val']) }}

Using Models in the view is more tricky, you could either embed a PHP block

// some/view.volt
<?php
$mdl = SomeModel::findFirst();
?>

{{ mdl.getName() }}

or create a helper service:

// ModelHelper.php
class ModelHelper
{
    public function create($modelName, array $assign=[])
    {
        return new $modelName($assign);
    }
    public function findFirst($modelName, $parameters=null) {
        $a = func_get_args();
        $modelName = array_shift($a);
        return forward_static_call_array([$modelName,'findFirst'], $a);
    }
}
// services.php
$di->set('modelHelper', function() {
    return new ModelHelper;
});
// some/view.volt
{{ modelHelper.findFirst('SomeModel', ['conditions'=>'id=2'])->getName() }}

Sending request? It's only possible with some ajax-like things. Why you dont like passing data through controllers? I think this is not necessary

I really don't see how there can be a good reason for accessing the database in a View. The View should only contain code that is used to display data. That paradigm helps keep things tidy. If you want to retrieve data, you should use the Controller, then pass the retrieved data to the View.

Thanks for the responses. I realise I should probably have made clear - I don't want to access the database from the view. The system we are making allows authenticated users to edit certain volt files (so that the client can change the title or whatever on their own website). However, I don't trust them with unrestricted access to make any request to the database and so I wanted to check that they wouldn't be able to do that if they could only edit the volt files - provided I sanitise the input and stop them submitting anything with php tags everything will be fine, thanks.