How can you create and use a Phalcon model?

How can you create and use a Phalcon model?

To create and use a Phalcon model, follow these minimal steps:

1. Create the Model Class

In Phalcon, models are typically created to interact with database tables. Here’s how you define a simple model:

Example

<?php
use Phalcon\Mvc\Model;

class User extends Model
{
    public $id;
    public $name;
    public $email;
}
?>

2. Set Up the Database Connection

In your DI (Dependency Injection) container, set up the database connection:

Example

<?php
use Phalcon\Di\FactoryDefault;
use Phalcon\Db\Adapter\Pdo\Mysql as DbAdapter;

$di = new FactoryDefault();

$di->set('db', function() {
    return new DbAdapter([
        'host'     => 'localhost',
        'username' => 'root',
        'password' => '',
        'dbname'   => 'phalcon_db'
    ]);
});
?>

3. Use the Model in the Controller

In your controller, you can use the model to interact with the database:

Example

<?php
class UserController extends \Phalcon\Mvc\Controller
{
    public function indexAction()
    {
        // Fetch all users
        $users = User::find();
        
        // Fetch a specific user by ID
        $user = User::findFirst(1);

        // Render the data
        $this->view->users = $users;
    }
}
?>

4. CRUD Operations

You can use Phalcon models for basic CRUD operations:

  • Create/Insert:

Example

<?php
$user = new User();
$user->name = 'John Doe';
$user->email = 'john@example.com';
$user->save();
?>

Update:

Example

<?php
$user = User::findFirst(1);
$user->name = 'Updated Name';
$user->save();
?>

Delete:

Example

<?php
$user = User::findFirst(1);
$user->delete();
?>

Related Questions & Topics