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

can i pass the model as argument in a method the controller?

hello, i am begginer in phalcon and i want know how step the model as argument in a method the controller


use \Phalcon\Mvc\Controller as Controller;

class UserController extends Controller{
    public function loginAction(User $users){
        $users->startAction();
    }
}

the other file


use \Phalcon\Phalcon\Mvc\Model as Model;
class User extends Model{
    public function startAction(){
        echo "LOL";
    }

}

i donĀ“t know how to add the route of that model? use include or require or namespace?



7.2k
Accepted
answer

In the controller method you must be separated arguments with comma " , ".

Maybe you could instance object class within controller method, and later pass parameter, For example:

use \Phalcon\Mvc\Controller as Controller;

class UserController extends Controller{

    public function loginAction(){
        $user = new User();
        $users->startAction($parameter);
    }

}


17.7k
edited Feb '15

but this can be? pass the model as argument?

edited Feb '15

I'm not completely sure, but probably not. In the manual invo tutorial, you can pass an id from the URL like something/edit/15, you get it via the action parameter editAction($id) { echo $id; // 15 }. That to me is the extent of passing value by way of action arguments. Don't think other frameworks can pass models via action parameter either, usually just persist by some index key, the usual way persistence is achieved in a web app.

If you want the data to be persistent across several actions, there is the session where you can store a serialized model instance maybe. Or perform save one the first action, where you get a new row id, then update on the rest of the actions. Or simply store data as an array in the session until you want to save it at a later point. I'm guessing your data entry requires multiple pages, like a multi page quiz/survey, shopping cart checkout process?



1.7k

@NelsonJPG: Phalcon does not provide an auto-model binding so you have to create the model from submited form values like

$user->name = $this->request->getPost('name');
//....other assignment here...
$user->save();

Actually with HMVC (https://github.com/phalcon/mvc/tree/master/hmvc), you can serialize an object, and pass it via the params key, not sure its a good idea or not but can be done.



17.7k

Thanks Edward, this solved my problem ... in the invo example they pass an object as an argument in the SessionController. I just do not know why I was saying that they had an error .. but equally thanks

Actaully, the hmvc example there doesn't really work out of the box sorry, the sub mvc call doesn't do anything with views.

On the invo example, the method private function _registerSession($user) is not an 'action', just something used internally by the controller.