Phalcon - 模型

MVC 架构中的模型包括应用程序的逻辑。模型是与数据库交互的核心。它应该能够根据用户的请求管理记录的更新、删除、插入和获取。

要了解 Phalcon PHP 框架中的模型交互,应遵循以下步骤。

步骤 1 − 创建数据库。

对于任何 LAMP、WAMP、XAMPP 软件堆栈,借助 phpmyadmin 数据库工具创建数据库都非常容易。

以下是创建数据库的 SQL 查询。

创建数据库 <database-name>

步骤 2 −在 phpmyadmin 部分中,单击"数据库"选项卡,输入数据库名称,然后单击"创建"按钮,如以下屏幕截图所示。

phpmyadmin

步骤 3 − 成功创建数据库后,创建一个表,该表将有助于其关联以在 Phalcon 框架中创建模型。

使用以下查询创建一个名为"users"的新表。

DROP TABLE IF EXISTS `users`;  

CREATE TABLE `users` ( 
   `id` int(11) NOT NULL AUTO_INCREMENT, 
   `name` varchar(25), 
   `emailid` varchar(50), 
   `contactNumber` number 
   PRIMARY KEY (`id`) 
) 
ENGINE = InnoDB DEFAULT CHARSET = utf8; 

一旦创建了表,其结构将如以下屏幕截图所示。

Table Created

步骤 4 − 要创​​建与我们在上述步骤中创建的"Users"表关联的模型,请打开命令提示符实例。重定向到适当的项目路径很重要。在此之前,必须检查数据库配置是否已正确设置,如以下屏幕截图所示。

users

步骤 5 − 使用以下命令在 Phalcon 框架中创建任何模型。

phalcon model <model-name>

以下是执行上述命令后的输出。

Result

这意味着模型已成功创建。

第 6 步 − 模型成功创建位于 models 文件夹中。使用以下路径查看模型的创建位置。

C:\xampp\htdocs\demo1\app\models

以下是 Users.php 的完整代码。

<?php  

class Users extends \Phalcon\Mvc\Model {
   /**      
      *      
      * @var integer 
      * @Primary 
      * @Identity
      * @Column(type = "integer", length = 11, nullable = false)      
   */      

   public $id; 
   /**
      *
      * @var string
      * @Column(type = "string", length = 25, nullable = true)      
   */ 

   public $name; 
   /**
      *
      * @var string
      * @Column(type = "string", length = 50, nullable = true)
   */      

   public $emailid; 
   /**
      *
      * @var integer
      * @Column(type = "integer", length = 11, nullable = true)
   */      

   public $contactNumber; 
   /**
      * Returns table name mapped in the model.
      *
      * @return string
   */      

   public function getSource() {
      return 'users';
   }  
   /**
      * Allows to query a set of records that match the specified conditions
      *
      * @param mixed $parameters
      * @return Users[]
   */ 

   public static function find($parameters = null) { 
      return parent::find($parameters);
   }  
   /**
      * Allows to query the first record that match the specified conditions
      *
      * @param mixed $parameters
      * @return Users
   */   
   
   public static function findFirst($parameters = null) {
      return parent::findFirst($parameters);
   } 
}

第 7 步 − 控制器与模型和视图交互以获取必要的输出。与模型一样,使用以下命令终端创建控制器。

Phalcon controller <controller-name> 

成功执行上述命令后,输出如下。

Sucessful Execution

以下是 UserController.php 的代码。

<?php  

class UsersController extends \Phalcon\Mvc\Controller { 
   public function indexAction() { 
      echo "Users Controller has been called"; 
   } 
}

如果我们点击以下 URL − http://localhost/demo1/users,将显示输出

demo1 Window