tenolo / open-graph-bundle
一个 Symphony OpenGraph 插件
Requires
- php: ~5.6|~7.0
- euskadi31/opengraph: ~1.0
- symfony/config: ~2.8|~3.4|~4.0
- symfony/dependency-injection: ~2.8|~3.4|~4.0
- symfony/framework-bundle: ~2.8|~3.4|~4.0
- symfony/http-kernel: ~2.8|~3.4|~4.0
- symfony/twig-bundle: ~2.8|~3.4|~4.0
- twig/twig: ~1.34|~2.0
This package is auto-updated.
Last update: 2024-08-29 04:37:12 UTC
README
OpenGraphBundle
TenoloOpenGraphBundle 是一种简单的方法,用于改进如何在 Symfony2 应用程序中管理 OpenGraph。
注意:OpenGraph 是一种由许多网站(Facebook、Twitter、Google 等)使用的标准协议,用于获取有关您内容的更精确信息。
这个插件的想法是将您的应用程序中的每个实体与一个 OpenGraph 映射 关联起来,这是一个能够为您的实体创建 OpenGraph 文档的服务。
它也可以与任何其他类型的数据一起工作。
安装
安装非常快速
1. 使用 Composer 下载
通过运行以下命令将插件添加到您的 composer.json
文件中:
composer require tenolo/open-graph-bundle
2. 在您的内核中启用它
在您的 app/AppKernel.php
文件中启用该插件;
<?php // app/AppKernel.php public function registerBundles() { $bundles = array( // ... new Tenolo\Bundle\OpenGraphBundle\TenoloOpenGraphBundle(), ); }
使用
TenoloOpenGraphBundle 将将...
- 实体 与...
- ... 或者 其他数据,如应用程序中的数组 与...
- OpenGraph 映射 关联起来,这是这些实体的 OpenGraph 方式定义
让我们用一个例子来更好地理解:一篇博客文章。
您的实体
对于一篇博客文章,您可能有一个这样的实体
<?php namespace Acme\DemoBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * @ORM\Table() * @ORM\Entity */ class BlogPost { /** * @ORM\Column(type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** * @ORM\Column(type="string", length=255) */ private $title; /** * @ORM\Column(type="text") */ private $content; }
它的 OpenGraph 映射
与您的实体关联的映射将是一个实现 Tenolo\Bundle\OpenGraphBundle\Map\OpenGraphMapInterface
的类,以及该接口的两个必需方法:map(DocumentWriterInterface $document, $data)
和 supports($data)
。
例如,我们的映射可能看起来像这样
<?php namespace Acme\DemoBundle\OpenGraph; use Acme\DemoBundle\Entity\BlogPost; use Tenolo\Bundle\OpenGraphBundle\OpenGraph\DocumentWriterInterface; use Tenolo\Bundle\OpenGraphBundle\Map\OpenGraphMapInterface; use Opengraph\Opengraph; class BlogPostMap implements OpenGraphMapInterface { /** * @inheritdoc * @var BlogPost $data */ public function map(DocumentWriterInterface $document, $data) { $document->append(OpenGraph::OG_SITE_NAME, 'MyBlog'); $document->append(OpenGraph::OG_TYPE, OpenGraph::TYPE_ARTICLE); $document->append(OpenGraph::OG_TITLE, $data->getTitle()); } /** * @inheritdoc */ public function supports($data) { return $entity instanceof BlogPost; } }
supports
方法声明了此映射能够处理哪种类型的实体。 map
方法创建一个表示给定实体的 OpenGraph 文档。
创建后,我们还需要将我们的类注册到 OpenGraph 管理器中。为此,我们将需要使用 tenolo_open_graph.map
标签。
services: acme_demo.open_graph.blog_post_map: class: Acme\DemoBundle\OpenGraph\BlogPostMap tags: - { name: tenolo_open_graph.map }
使用映射
我们的映射已经注册,所以我们可以将其用于任何我们想要渲染的地方。例如,使用 Twig
<html> <head> <title>Blog post</title> {{ opengraph_render(blogPost) }} <!-- blogPost should be an instance of BlogPost --> </head> <body> ... </body> </html>
注意:如果没有任何映射能够处理在
opengraph_render
中提供的实体,将抛出一个NotSupported
异常。
另一个注意:归功于 tgalopin 的贡献和灵感
只是说说;)