前言:本节将介绍如何创建model。
1.创建数据库
打开xampp的phpmyadmin,创建一个数据库store
然后,创建一个数据表users如下
CREATE TABLE `users` (
`id` int(128) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`email` varchar(255) NOT NULL,
`contact` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
2.注册app/config/config.php
这里把store数据库加了进去。
<?php
/*
* Modified: prepend directory path of current file, because of this file own different ENV under between Apache and command line.
* NOTE: please remove this comment.
*/
defined('BASE_PATH') || define('BASE_PATH', getenv('BASE_PATH') ?: realpath(dirname(__FILE__) . '/../..'));
defined('APP_PATH') || define('APP_PATH', BASE_PATH . '/app');
return new \Phalcon\Config([
'database' => [
'adapter' => 'Mysql',
'host' => 'localhost',
'username' => 'root',
'password' => '',
'dbname' => 'store',
'charset' => 'utf8',
],
'application' => [
'appDir' => APP_PATH . '/',
'controllersDir' => APP_PATH . '/controllers/',
'modelsDir' => APP_PATH . '/models/',
'migrationsDir' => APP_PATH . '/migrations/',
'viewsDir' => APP_PATH . '/views/',
'pluginsDir' => APP_PATH . '/plugins/',
'libraryDir' => APP_PATH . '/library/',
'cacheDir' => BASE_PATH . '/cache/',
'baseUri' => '/',
]
]);
3.创建model
在htdocs/store的命令行中输入:
phalcon model users
成功。
vscode的app/models/也出现了Users.php文件,其内容如下:
<?php
use Phalcon\Validation;
use Phalcon\Validation\Validator\Email as EmailValidator;
class Users extends \Phalcon\Mvc\Model
{
/**
*
* @var integer
*/
public $id;
/**
*
* @var string
*/
public $name;
/**
*
* @var string
*/
public $email;
/**
*
* @var integer
*/
public $contact;
/**
* Validations and business logic
*
* @return boolean
*/
public function validation()
{
$validator = new Validation();
$validator->add(
'email',
new EmailValidator(
[
'model' => $this,
'message' => 'Please enter a correct email address',
]
)
);
return $this->validate($validator);
}
/**
* Initialize method for model.
*/
public function initialize()
{
$this->setSchema("store");
$this->setSource("users");
}
/**
* Allows to query a set of records that match the specified conditions
*
* @param mixed $parameters
* @return Users[]|Users|\Phalcon\Mvc\Model\ResultSetInterface
*/
public static function find($parameters = null): \Phalcon\Mvc\Model\ResultsetInterface
{
return parent::find($parameters);
}
/**
* Allows to query the first record that match the specified conditions
*
* @param mixed $parameters
* @return Users|\Phalcon\Mvc\Model\ResultInterface
*/
public static function findFirst($parameters = null)
{
return parent::findFirst($parameters);
}
}
总结 : 迄今为止第一个model创建成功。