We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Accessing namespace models in volt

Hi, I have all my models with namespace MyApp\Models My question is how to directly access the model directly from volt?

For example I have a model of foo in Foo.php:

<?php
namespace MyApp\Models;
class Foo extends \Phalcon\Mvc\Model 
{
}

I want to retrive all record in Foo in my bar.volt like

{% for x in MyApp\Models\Foo.find() %}
    Name: {{x.name}}<br>
{% endfor %}

But it will generate error. Pls Help.



98.9k
Accepted
answer

Calling static functions in volt is still not supported, we hope support it soon, from now you can use php there:

<?php foreach (MyApp\Models\Foo::find() as $x) { ?>
Name: {{x.name}}<br>
<?php } ?>

That's worked great. Volt is awesome :) Thanks Phalcon.



17.8k

very good, in volt template ,can use php tag?

I know this thread is a little old but it was recently brought up in Discord.

This example is not an idiomatic usage of the MVC pattern and while Volt and phtml could be flexible enough to perform this operation. You should not be making the template responsible for querying the DB.

Accessing data should be handled in your Controller or Handler layer then the results passed to Volt via the view bag.

The opinion of where to keep "business logic" differs from framework to framework but I think the 10000 ft view:

  • Put data query(relation), Validation, and Transformation in the Model.
  • Data retrieval should occur in the Controller
  • Presentation should happen in the view with as little logic as possible.

You will thank yourself later for keeping Templates as logicless as possible. Especially when you consider how much harder it is to unit test your Model and Controller classes when they are bound to the views.

Please don't do this if only to avoid the pains in being able to test your Controller when some of your business logic will live in the view

Calling static functions in volt is still not supported, we hope support it soon, from now you can use php there:

<?php foreach (MyApp\Models\Foo::find() as $x) { ?>
Name: {{x.name}}<br>
<?php } ?>