Skip to content

Example

Sid Roberts edited this page Mar 31, 2019 · 3 revisions

DI

$di->set(
    "boundModels",
    function () {
        $boundModels = new \Sid\Phalcon\BoundModels\Manager();

        return $boundModels;
    },
    true
);

Model

namespace Sid\Models;

use Phalcon\Mvc\Model;

class Posts extends Model
{
    public $categorySlug;
    public $postSlug;

    // ...
}

Controller

There are 3 important methods: get(), create() and getOrCreate():

  • get() uses \Phalcon\Mvc\Model::findFirst() to get a model instance from the database.
  • create() creates a model instance from dispatcher parameters but does not save it.
  • getOrCreate() uses get() and then create() if it can't find a record in the database.

They all use the same parameters and work in the following way:

namespace Sid\Controllers;

use Phalcon\Mvc\Controller;
use Sid\Models\Posts;

/**
 * @RoutePrefix("/post")
 */
class PostController extends Controller
{
    /**
     * @Route("/{categorySlug:[A-Za-z0-9\-]+}/{postSlug:[A-Za-z0-9\-]+}")
     */
    public function postAction()
    {
        // Infer attributes
        $post = $this->boundModels->get(
            Posts::class
        );

        // Force only categorySlug to be used to find the model
        $post = $this->boundModels->get(
            Posts::class,
            [
                "categorySlug",
            ]
        );

        // ...
    }
}
Clone this wiki locally