miniframe / orm
v1.x-dev
2022-11-25 19:42 UTC
Requires
- php: >=7.3
- miniframe/annotation: v1.x-dev
- miniframe/core: ^1.0
Requires (Dev)
- garrcomm/phpunit-helpers: v1.x-dev
- phpstan/phpstan: ^1.9
- phpunit/phpunit: ^9.4
- squizlabs/php_codesniffer: ^3.5
Suggests
- ext-mysqli: When using the MySQL engine, the mysqli extension is required.
This package is auto-updated.
Last update: 2024-09-25 23:35:50 UTC
README
此包为 Miniframe PHP 框架添加了一个简单的 ORM。
如何配置
首先,将中间件添加到框架中
[framework]
middleware[] = Miniframe\ORM\Middleware\ORM
然后,添加一个引擎,对于 MySQL 来说,意味着
[orm]
engine = MySQL
mysql_username = miniframe
mysql_password = miniframepw
mysql_database = miniframedb
mysql_hostname = localhost
; mysql_port = 3306
; mysql_socket = /var/run/mysqld/mysqld.sock
如何使用
首先定义实体。示例请参考这里: Example.php
现在,你可以在你的代码中使用这个实体
use App\Model\Example;
use Miniframe\Core\Registry;
use Miniframe\ORM\Middleware\ORM;
/* @var $entity Example */
/* @var $entities Example[] */
// Create a repository for the Example entity
$repository = Registry::get(ORM::class)->getRepository(Example::class);
// To get all entities
$entities = $repository->findAll();
// To get an entity by it's unique identifier
$entity = $repository->find(1);
// To get an entity by a specific column
$entity = $repository->findOneBy(['name' => 'Foo bar']);
// To get multiple entities by a specific column
$entities = $repository->findBy(['tag' => 'Foo']);
// To modify and save an entity to the database
$entity->setName('Foo bar');
$entity->setTag('foo');
$repository->save($entity);
// To delete an entity from the database
$repository->delete($entity);
没有 flush() 也无需 persist(),请注意!
这个 ORM 被设计得简单,且占用内存少。因此,没有实体中央注册或缓存。
为什么这很重要?这解释了它的相关性
use App\Model\Example;
use Miniframe\Core\Registry;
use Miniframe\ORM\Middleware\ORM;
/* @var $entity1 Example */
/* @var $entity2 Example[] */
// Create a repository for the Example entity
$repository = Registry::get(ORM::class)->getRepository(Example::class);
$entity1 = $repository->find(1);
$entity2 = $repository->find(1);
if ($entity1 == $entity2) {
echo 'They are the same at this point' . PHP_EOL;
}
$entity1->setName('foo bar');
if ($entity1 == $entity2) {
echo 'But they are not the same anymore' . PHP_EOL;
}
有些 ORM 中,第二个 if()
语句仍然会匹配,因为它是同一实体的引用。在这个 ORM 中,情况并非如此。
针对 Windows 开发者
在 bin
文件夹中,存在一些批处理文件,以简化开发过程。
如果你安装了 Docker Desktop for Windows,你可以使用 bin\composer.bat、bin\phpcs.bat、bin\phpunit.bat、bin\phpstan.bat 和 bin\security-checker.bat 作为 Composer、CodeSniffer、PHPUnit、PHPStan 和安全检查器的快捷方式,无需在机器上安装 PHP 和其他依赖项。
在 Bitbucket Pipelines 中也使用了相同的 Docker 容器和工具来自动测试此项目。