symfony4 orm_介绍Neo4j Symfony捆绑包

symfony4 orm

This article was peer reviewed by Wern Ancheta and Christophe Willemsen. Thanks to all of SitePoint’s peer reviewers for making SitePoint content the best it can be!

这篇文章由Wern AnchetaChristophe Willemsen进行了同行评审。 感谢所有SitePoint的同行评审人员使SitePoint内容达到最佳状态!



为什么是图? (Why Graphs?)

There is no such thing as disconnected information, no matter where you look – people, events, places, things, documents, applications and the information about them is all heavily connected. As the volume of data grows, so does the number and dynamicity of its connections. And if you’ve tried in the past to store and query that highly connected, semi-structured data in any database, you probably experienced a lot of challenges.

无论您在何处看,都不会出现信息断开的情况–人员,事件,地点,事物,文档,应用程序以及与它们相关的信息都是紧密相连的。 随着数据量的增长,其连接的数量和动态性也在增长。 而且,如果您过去曾尝试在任何数据库中存储和查询高度连接的半结构化数据,那么您可能会遇到很多挑战。

Example graph

本机图数据库中的标签属性图 (The Labeled Property Graph in a native Graph Database)

Neo4j was built to handle exactly this real-world information without compromising on the number and types of connections you can have relating your entities. It is an open-source NoSQL database that uses the Labeled Property Graph to store the entities of your domain model (diagram) as Nodes and their connections as Relationships each of which can have arbitrary properties.

Neo4j的构建完全可以处理这些现实世界的信息,而不会影响您与实体相关的连接的数量和类型。 它是一个开放源代码的NoSQL数据库,该数据库使用“标签的属性图”将域模型(图)的实体存储为“ 节点”,并将它们的连接存储为“ 关系”,每个实体都可以具有任意属性。

Nodes and releationships with properties

Neo4j is not just a graph layer on top of another database but a full blown, transactional (ACID) database with everything from managing pages of records on disk to providing a scalable, secure cluster. And as a native graph database it uses dedicated data structures to store and query highly connected data efficiently. Unlike in other databases, (complex) JOIN queries are not computed repeatedly at query time. Instead, relationships between entities are stored directly. During querying the database engine can use direct record-pointers for constant time lookups.

Neo4j不仅是另一个数据库之上的图形层,而且是功能完善的事务(ACID)数据库,其内容从管理磁盘上的记录页面到提供可伸缩的安全群集,应有尽有。 作为本地图形数据库,它使用专用的数据结构来有效地存储和查询高度连接的数据。 与其他数据库不同,(复杂)JOIN查询不会在查询时重复计算。 而是,实体之间的关系直接存储。 在查询期间,数据库引擎可以使用直接记录指针进行恒定时间查找。

开放的Cypher查询语言 (The open Cypher Query Language)

This doesn’t just extend to modeling or storage, even the Cypher graph query language that comes with Neo4j is focused around graph patterns, this time represented as ASCII-art in your query: (dan:Person {name:"Dan"})-[:LOVES]->(ann:Person {name:"Ann"}), which make your queries extremely readable even for non-developers, e.g. here is a recommendation query (“customers like you also bought this”):

这不仅扩展到建模或存储,甚至Neo4j随附的Cypher图形查询语言都集中于图形模式,这次在查询中表示为ASCII艺术: (dan:Person {name:"Dan"})-[:LOVES]->(ann:Person {name:"Ann"}) ,即使对于非开发人员,您的查询也非常可读,例如,这是一个推荐查询(“像您一样的客户也购买了此”):

MATCH (c:Customer)-[:BOUGHT]->(:Product)<-[:BOUGHT]-(o:Customer)-[:BOUGHT]->(reco:Product)
WHERE c.id = 123 AND NOT (c)-[:BOUGHT]->(reco)
RETURN reco.name, count(*) as frequency
ORDER BY frequency DESC LIMIT 10;

Symfony,PHP的快速开发框架 (Symfony, a rapid development framework for PHP)

Symfony is the role model of frameworks for modern PHP. The framework has a component approach and has been around for the last 11 years. From the Symfony ecosystem we’ve seen projects like Composer, Twig, Swiftmailer, Assetic, Monolog and many more. Thanks to the component approach, it has been made easy for other projects and frameworks to reuse code from Symfony. Projects like Laravel, Silex, Sylius, Drupal, phpBB, eZ are all using Symfony components.

Symfony是现代PHP框架的榜样。 该框架采用组件化方法,并且已经使用了近11年。 在Symfony生态系统中,我们看到了诸如Composer,Twig,Swiftmailer,Assetic,Monolog等项目。 由于采用了组件方法,其他项目和框架可以轻松重用Symfony的代码。 诸如Laravel,Silex,Sylius,Drupal,phpBB,eZ之类的项目都使用Symfony组件。

A key factor of Symfony’s success is the flexibility of the framework in combination with the ease of use. The standard edition of Symfony comes with Doctrine as default database layer abstraction which supports some major databases like MySQL and MongoDB. But neither the database layer nor Doctrine is a primary citizen in Symfony. They could easily be replaced by something else.

Symfony成功的关键因素是框架的灵活性以及易用性。 Symfony的标准版随附Doctrine作为默认数据库层抽象,它支持某些主要数据库,如MySQL和MongoDB。 但是数据库层和Doctrine都不是Symfony的主要公民。 它们很容易被其他东西代替。

介绍Symfony Neo4j捆绑包 (Introducing Symfony Neo4j Bundle)

To provide a smooth integration between Neo4j and Symfony we’ve created the SymfonyNeo4jBundle. It wraps the excellent PHP community client by Graphaware and creates a solid Symfony experience. Thanks to the WebProfiler integration, you will see all your database calls, all the queries and their results. You will even have a view over any exceptions that are thrown when interacting with the database. You will also get detailed statistics about each database call. This makes debugging your application way easier.

为了在Neo4j和Symfony之间提供平滑的集成,我们创建了SymfonyNeo4jBundle。 它包装了Graphaware优秀PHP社区客户端,并提供了坚实的Symfony体验。 由于WebProfiler集成,您将看到所有数据库调用,所有查询及其结果。 您甚至可以查看与数据库交互时引发的所有异常。 您还将获得有关每个数据库调用的详细统计信息。 这使调试应用程序的方式变得更加容易。

The bundle also integrates the client events with the Symfony event dispatcher. You could now create event subscribers that listen to the interactions with Neo4j e.g. for integration with MonologBundle to log all your database queries.

该捆绑软件还将客户端事件与Symfony事件分派器集成在一起。 现在,您可以创建事件订阅者,以监听与Neo4j的交互,例如与MonologBu​​ndle集成以记录所有数据库查询。

The bundle is not opinionated in how you are using Neo4j. Using the OGM is optional. Advanced Neo4j users will have full control over the client and what Cypher gets executed.

该捆绑软件对您使用Neo4j的方式没有意见。 使用OGM是可选的。 高级Neo4j用户将完全控制客户端以及执行Cypher的程序。

像Doctrine这样的API (An API like Doctrine)

For developers who are familiar with Doctrine, they will know how to use GraphAware’s OGM (Object Graph Mapper). The OGM has an EntityManager that implements Doctrine’s ObjectManager interface, which gives you functions like “find”, “remove”, “persist” and “flush”. Developers will have the exact same experience working with models from Neo4j’s OGM compared to Doctrine’s MySQL EntityManagers.

对于熟悉Doctrine的开发人员,他们将知道如何使用GraphAware的OGM(对象图映射器)。 OGM有一个EntityManager,它实现了Doctrine的ObjectManager接口,该接口为您提供了“查找”,“删除”,“持久”和“刷新”之类的功能。 与DoctrineMySQL EntityManagers相比,开发人员在使用Neo4j的OGM模型上将具有完全相同的经验。

组态 (Configuration)

Like in most modern frameworks, Symfony separates configuration from the code. This is good software practice which the Neo4jBundle adheres to. It provides the ability to easily configure multiple connections, multiple clients and multiple entity managers. For each connection you can decide if you want to use HTTP or the new binary “bolt” protocol.

像在大多数现代框架中一样,Symfony将配置与代码分开。 Neo4jBundle遵循的这是良好的软件实践。 它提供了轻松配置多个连接,多个客户端和多个实体管理器的功能。 对于每个连接,您可以决定要使用HTTP还是新的二进制“螺栓”协议。

Thanks to Symfony’s configuration component, you may use Yaml, XML or PHP to specify your configuration. The default configuration will set up one connection to 127.0.0.1:7474 with the defaults username / password.

感谢Symfony的配置组件,您可以使用Yaml,XML或PHP来指定您的配置。 默认配置将使用默认的用户名/密码建立到127.0.0.1:7474一个连接。

Symfony-Neo4j-Bundle入门 (Getting started with the Symfony-Neo4j-Bundle)

After installing the the bundle you may start using the clients

安装捆绑软件后,您可以开始使用客户端

$client = $this->get('neo4j.client');
$results = $client->run('MATCH (n:Movie) RETURN n LIMIT 5');
foreach ($results->records() as $record) {
   $node = $record->get('n');
   echo $node->get('title'); // "The Matrix"
}

If you are used to Doctrine you may want to use the OGM. You need to add annotations to your models so the OGM will understand and map the properties properly.

如果您习惯了教义,则可能要使用OGM。 您需要在模型中添加注释,以便OGM能够正确理解和映射属性。

use GraphAware\Neo4j\OGM\Annotations as OGM;

/**
 * @OGM\Node(label="User")
 */
class User
{
    /** @OGM\GraphId() */
    protected $id;

    /** @OGM\Property(type="string") */
    protected $name;

    /** @OGM\Property(type="int") */
    protected $age;

    // Getters and setters
}
$em = $this->get('neo4j.entity_manager');

$bart = new User('Bart Johnson', 33);
$em->persist($bart);
$em->flush();

// Retrieve from database
$john = $em->getRepository(User::class)->findOneBy('name', 'John Doe');
echo $john->getAge();

Here is an example of what the profiler may look like:

这是探查器可能的示例:

Example of the Symfony profiler page

关系和关系实体 (Relationship and relationship entities)

The major difference from Doctrine and MySQL is that relationships are first class citizens in Neo4j. They are as important as the nodes themselves. To create a simple relationship between a person and a movie you would use the @OGM\Relationship annotation.

与Doctrine和MySQL的主要区别在于关系是Neo4j中的头等公民。 它们与节点本身一样重要。 要在人与电影之间建立简单的关系,可以使用@OGM\Relationship批注。

use GraphAware\Neo4j\OGM\Annotations as OGM;
use GraphAware\Neo4j\OGM\Common\Collection;

/**
*
* @OGM\Node(label="Person")
*/
class Person
{
   /**
    * @var int
    *
    * @OGM\GraphId()
    */
   protected $id;

   // other code

   /**
    * @var Movie[]|Collection
    *
    * @OGM\Relationship(type="ACTED_IN", direction="OUTGOING", collection=true, mappedBy="actors", targetEntity="Movie")
    */
   protected $movies;

   public function __construct()
   {
       $this->movies = new Collection();
   }

   // other code

   /**
    * @return Movie[]|Collection
    */
   public function getMovies()
   {
       return $this->movies;
   }
}

The Movie class has an INCOMING relationship from Person.

Movie类与Person具有INCOMING关系。

use GraphAware\Neo4j\OGM\Annotations as OGM;
use GraphAware\Neo4j\OGM\Common\Collection;

/**
*
* @OGM\Node(label="Movie")
*/
class Movie
{
   /**
    * @var int
    *
    * @OGM\GraphId()
    */
   protected $id;

   // other code

   /**
    * @var Person[]|Collection
    *
    * @OGM\Relationship(type="ACTED_IN", direction="INCOMING", collection=true, mappedBy="movies", targetEntity="Person")
    */
   protected $actors;

   public function __construct()
   {
       $this->actors = new Collection();
   }

   // other code

   /**
    * @return Person[]|Collection
    */
   public function getActors()
   {
       return $this->actors;
   }
}

The relationship itself can have also properties. Example if a User rates a Movie then the relationship would probably have a score. This can be achieved with relationship entities. Read more about them at the OGM’s documentation.

关系本身也可以具有属性。 例如,如果用户对电影进行评分,则该关系可能会得分。 这可以通过关系实体来实现。 在OGM的文档中了解有关它们的更多信息。

示例项目 (Example project)

There is an example project that you may use to test the bundle. Use the the steps below to install the project:

您可以使用一个示例项目来测试捆绑软件。 使用以下步骤安装项目:

git clone git@github.com:neo4j-examples/movies-symfony-php-bolt.git
composer install

Import data fixture (https://neo4j.com/developer/example-project/#_data_setup)

导入数据装置(https://neo4j.com/developer/example-project/#_data_setup)

php bin/console server:run

Go to http://127.0.0.1:8000/

转到http://127.0.0.1:8000/

There is more information about the bundle in the repository on Github. Please give us comments and feedback of what we did right and how we can improve. Feel free to raise issues or contribute to the project.

在Github上的存储库中有关于捆绑软件的更多信息。 请给我们有关我们做得正确以及如何改进的意见和反馈。 随时提出问题或为项目做贡献。

资源: (Resources:)

翻译自: https://www.sitepoint.com/introducing-the-neo4j-symfony-bundle/

symfony4 orm

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值