1、数据库配置
官方文档地址:https://doc.swoft.org/master/zh-CN/db/config.html
默认是给出的主从配置,这里暂不考虑主从,config/properties/db.php
代码修改如下:
<?php
return [
'master' => [
'name' => 'master',
'uri' => [
'127.0.0.1:3306/test?user=root&password=root&charset=utf8mb4'
],
'minActive' => 8,
'maxActive' => 8,
'maxWait' => 8,
'timeout' => 8,
'maxIdleTime' => 60,
'maxWaitTime' => 3,
]
];
本地test
数据库。
数据库配置文件中各项参数具体什么作用,官方文档里都有介绍。
2、数据实体定义
官方文档:https://doc.swoft.org/master/zh-CN/db/entity.html
开始之前,在test
数据库里创建好news
数据表,表结构随你:
CREATE TABLE `news` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`title` varchar(255) NOT NULL DEFAULT '',
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=8 DEFAULT CHARSET=utf8mb4;
swoft 提供了内置命令帮助快速生成实体类:
php bin/swoft entity:create -d test news
执行成功之后,会在App\Models\Entity
目录下创建一个News.php
文件,代码如下:
<?php
namespace App\Models\Entity;
use Swoft\Db\Model;
use Swoft\Db\Bean\Annotation\Column;
use Swoft\Db\Bean\Annotation\Entity;
use Swoft\Db\Bean\Annotation\Id;
use Swoft\Db\Bean\Annotation\Required;
use Swoft\Db\Bean\Annotation\Table;
use Swoft\Db\Types;
/**
* @Entity()
* @Table(name="news")
* @uses News
*/
class News extends Model
{
/**
* @var int $id
* @Id()
* @Column(name="id", type="integer")
*/
private $id;
/**
* @var string $title
* @Column(name="title", type="string", length=255, default="")
*/
private $title;
/**
* @param int $value
* @return $this
*/
public function setId(int $value)
{
$this->id = $value;
return $this;
}
/**
* @param string $value
* @return $this
*/
public function setTitle(string $value): self
{
$this->title = $value;
return $this;
}
/**
* @return mixed
*/
public function getId()
{
return $this->id;
}
/**
* @return string
*/
public function getTitle()
{
return $this->title;
}
}
3、查询器使用
https://doc.swoft.org/master/zh-CN/db/query.html
Query::table(News::class)->orderBy("id","desc")->limit(3)->get()->getResult();
news
表排倒序取3条,结果集为数组。
在控制中实现,我们这里创建一个提供API的控制器,在App\Controllers\Api
目录下创建NewsController.php
,代码如下:
<?php
namespace App\Controllers\Api;
use App\Models\Entity\News;
use Swoft\Db\Query;
use Swoft\Http\Server\Bean\Annotation\Controller;
use Swoft\Http\Server\Bean\Annotation\RequestMapping;
use Swoft\Http\Server\Bean\Annotation\RequestMethod;
/**
* @Controller("/news")
*/
class NewsController
{
/**
* @RequestMapping(route="list", method={RequestMethod::GET})
*/
public function getList()
{
return return ["id"=>1,"title"=>"title11111"];
}
}
浏览器访问 http://localhost/news/list 页面响应一段json字符串。如:{"id":1,"title":"title11111"}