n1c01a5/n1c0quote-bundle

使用REST API管理报价的捆绑包

安装: 185

依赖: 0

建议者: 0

安全性: 0

星标: 0

关注者: 2

分支: 0

公开问题: 0

类型:symfony-bundle

dev-master 2015-11-08 01:33 UTC

This package is not auto-updated.

Last update: 2024-09-24 02:13:44 UTC


README

管理报价的捆绑包。

步骤 1: 设置捆绑包

A) 下载并安装 N1c0Quote

要安装 N1c0Quote,请运行以下命令

$ php composer.phar require n1c01a5/n1c0quote-bundle

B) 启用捆绑包

在内核中启用所需的捆绑包

<?php
// app/AppKernel.php

public function registerBundles()
{
    $bundles = array(
        // ...
        new FOS\RestBundle\FOSRestBundle(),
        new JMS\SerializerBundle\JMSSerializerBundle(),
        new Nelmio\ApiDocBundle\NelmioApiDocBundle(),
        new Bazinga\Bundle\HateoasBundle\BazingaHateoasBundle(),
        new Stof\DoctrineExtensionsBundle\StofDoctrineExtensionsBundle(),
        new N1c0\QuoteBundle\N1c0QuoteBundle(),
    );
}

FOSRestBundle, StofDoctrineExtensionsBundle 和 NelmioApiDocBundle 必须配置。此捆绑包需要 PHP 的 Diff 实现:"sebastian/diff": "*" (composer.json).

C) 启用 Http 方法覆盖

如此处所述启用 HTTP 方法覆盖

从 symfony 2.3 开始,您只需修改您的 config.yml

# app/config/config.yml

framework:
    http_method_override: true

步骤 2: 设置 Doctrine ORM 映射

ORM 实现没有为您的使用提供具体的 Quote 类,您必须创建一个。这可以通过扩展捆绑包提供的抽象实体并创建适当的映射来完成。

例如,报价实体

<?php
// src/MyProject/MyBundle/Entity/Quote.php

namespace MyProject\MyBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use N1c0\QuoteBundle\Entity\Quote as BaseQuote;

/**
 * @ORM\Entity
 * @ORM\ChangeTrackingPolicy("DEFERRED_EXPLICIT")
 */
class Quote extends BaseQuote
{
    /**
     * @ORM\Id
     * @ORM\Column(type="guid", length=36)
     * @ORM\GeneratedValue(strategy="UUID")
     */
    protected $id;
}

例如,论点实体

<?php
// src/MyProject/MyBundle/Entity/Argument.php

namespace MyProject\MyBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use N1c0\QuoteBundle\Entity\Argument as BaseArgument;

/**
 * @ORM\Entity
 * @ORM\ChangeTrackingPolicy("DEFERRED_EXPLICIT")
 */
class Argument extends BaseArgument
{
    /**
     * @ORM\Id
     * @ORM\Column(type="guid", length=36)
     * @ORM\GeneratedValue(strategy="UUID")
     */
    protected $id;

    /**
     * Quote of this argument
     *
     * @var Quote 
     * @ORM\ManyToOne(targetEntity="MyProject\MyBundle\Entity\Argument")
     */
    protected $quote;
}

在 app/config/config.yml 中添加

# N1c0QuoteBundle
n1c0_quote:
    db_driver: orm
    class:
        model:
            quote: MyProject\MyBundle\Entity\Quote
            argument: MyProject\MyBundle\Entity\Argument

entity_managers:
            default:
                mappings:
                    N1c0QuoteBundle: ~
                    MyBundleMyProjectBundle: ~

assetic:
    bundles:        ["N1c0QuoteBundle"]

步骤 3: 导入 N1c0QuoteBundle 路由文件

# /app/config/routing.yml
n1c0_quote:
    type: rest
    prefix: /api
    resource: "@N1c0Quote/Resources/config/routing.yml"

内容协商

每个资源都可以以不同的格式访问。

HTTP 动词

对于报价

GET

以 HTML 格式

curl -i localhost:8000/api/v1/quotes/10

以 JSON 格式

curl -i -H "Accept: application/json" localhost:8000/api/v1/quotes/10

POST

以 HTML 格式

curl -X POST -d "n1c0_quote_quote%5Btitle%5D=myTitle&n1c0_quote_quote%5Bbody%5D=myBody" https://:8000/api/v1/quotes

以 JSON 格式

curl -X POST -d '{"n1c0_quote_quote":{"title":"myTitle","body":"myBody"}}' https://:8000/api/v1/quotes.json --header "Content-Type:application/json" -v

PUT

以 JSON 格式

curl -X PUT -d '{"n1c0_quote_quote":{"title":"myNewTitle","body":"myNewBody https://:8000/api/v1/quotes/10 --header "Content-Type:application/json" -v

对于论点

GET

以 JSON 格式

curl -i -H "Accept: application/json" localhost:8000/api/v1/quotes/10/arguments

POST

以 JSON 格式

curl -X POST -d '{"n1c0_quote_argument":{"title":"myTitleArgument","body":"myBodyArgument"}}' https://:8000/api/v1/quotes/10/arguments.json --header "Content-Type:application/json" -v

PUT

以 JSON 格式

curl -X PUT -d '{"n1c0_quote_argument":{"title":"myNewTitleArgument","body":"myNewBodyArgument"}}' https://:8000/api/v1/quotes/10/arguments/11.json --header "Content-Type:application/json" -v 

PATCH

以 JSON 格式

curl -X PATCH -d '{"n1c0_quote_argument":{"title":"myNewTitleArgument"}}' https://:8000/api/v1/quotes/10/arguments/11.json --header "Content-Type:application/json" -v

HATEOAS REST

引入 HATEOAS 约束。

{
    "user": {
        "id": 10,
        "title": "myTitle",
        "body": "MyBody",
        "_links": {
            "self": { "href": "https://:8000/api/v1/quotes/10" }
        }
    }
}

FOSUserBundle 集成

默认情况下,报价是匿名的。可以使用 FOSUserBundle 认证来签名报价。

A) 设置 FOSUserBundle

首先您需要设置 FOSUserBundle。检查说明

B) 扩展 Quote 类

为了向报价添加作者,Quote 类应实现 SignedQuoteInterface 并在您的映射中添加一个字段。

例如在 ORM 中

<?php
// src/MyProject/MyBundle/Entity/Quote.php

namespace MyProject\MyBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use N1c0\QuoteBundle\Entity\Quote as BaseQuote;
use N1c0\QuoteBundle\Model\SignedQuoteInterface;
use Symfony\Component\Security\Core\User\UserInterface;

/**
 * @ORM\Entity
 */
class Quote extends BaseQuote implements SignedQuoteInterface
{
    // .. fields

    /**
     * Authors of the quote
     *
     * @ORM\ManyToMany(targetEntity="Application\UserBundle\Entity\User")
     * @var User
     */
    protected $authors;

    public function __construct()
    {
        $this->authors = new \Doctrine\Common\Collections\ArrayCollection();
    }

    /**
     * Add author 
     *
     * @param Application\UserBundle\Entity\User $user
     */
    public function addAuthor(\Application\UserBundle\Entity\User $user)
    {
        $this->authors[] = $user;
    }

    /**
     * Remove user
     *
     * @param Application\UserBundle\Entity\User $user
     */
    public function removeUser(\Application\UserBundle\Entity\User $user)
    {
        $this->authorss->removeElement($user);
    }

    public function getAuthors()
    {
        return $this->authors;
    }

    public function getAuthorsName()
    {
        return $this->authors ?: parent::getAuthorsName(); 
    }
}

步骤 7: 添加基于角色的 ACL 安全性

注意

此捆绑包支持不同的安全设置。您还可以查看 添加 Symfony2 内置的 ACL 安全性

QuoteBundle 还提供了根据特定用户具有的角色配置权限的能力。请参阅下面的配置示例,了解如何自定义用于权限的默认角色。

要配置基于角色的安全性,覆盖 Acl 服务

# app/config/config.yml

n1c0_quote:
    acl: true
    service:
        acl:
            quote:  n1c0_quote.acl.quote.roles
        manager:
            quote:  n1c0_quote.manager.quote.acl

要更改特定操作所需的角色,修改 acl_roles 配置键

# app/config/config.yml

n1c0_quote:
    acl_roles:
        quote:
            create: IS_AUTHENTICATED_ANONYMOUSLY
            view: IS_AUTHENTICATED_ANONYMOUSLY
            edit: ROLE_ADMIN
            delete: ROLE_ADMIN

使用标记解析器

N1c0Quote 捆绑包允许开发人员实现 RawQuoteInterface,这将告诉捆绑包您的报价将被解析为标记语言。

您还需要在数据库中配置一个 rawBody 字段来存储解析后的报价。

use N1c0\QuoteBundle\Model\RawQuoteInterface;

class Quote extends BaseQuote implements RawQuoteInterface
{
    /**
     * @ORM\Column(name="rawBody", type="text", nullable=true)
     * @var string
     */
    protected $rawBody;
    
    ... also add getter and setter as defined in the RawQuoteInterface ...
}

当添加评论时,它会被解析,并使用评论的原始版本调用 setRawBody(),然后存储在数据库中,并在稍后渲染报价时显示。

支持任何标记语言,您只需要一个实现 Markup\ParserInterface 的桥接类,并返回要在页面上显示的报价的原始 html 解析结果。

要设置自己的自定义标记解析器,您需要定义一个实现上述接口的服务,并通知 N1c0QuoteBundle,相应地调整配置。

# app/config/config.yml

n1c0_quote:
    service:
        markup: your_markup_service

例如,使用 Sundown PECL 扩展作为标记服务

N1c0QuoteBundle 中的标记系统非常灵活,允许您使用任何存在解析器的语法语言。PECL 为 markdown 解析提供了一个名为 Sundown 的扩展,它比纯 PHP 实现的 markdown 解析器更快。

N1c0QuoteBundle 不包含此扩展的桥梁,但实现起来非常简单。

首先,您需要使用 PECL 安装 Sundown。 pecl install sundown

您希望在自己的应用程序包中创建以下服务。

<?php
// src/Vendor/QuoteBundle/Markup/Sundown.php

namespace Vendor\QuoteBundle\Markup;

use N1c0\QuoteBundle\Markup\ParserInterface;
use Sundown\Markdown;

class Sundown implements ParserInterface
{
    private $parser;

    protected function getParser()
    {
        if (null === $this->parser) {
            $this->parser = new Markdown(
                new \Sundown\Render\HTML(array('filter_html' => true)),
                array('autolink' => true)
            );
        }

        return $this->parser;
    }

    public function parse($raw)
    {
        return $this->getParser()->render($raw);
    }
}

以及用于启用此解析器桥梁的服务定义

# app/config/config.yml

services:
    # ...
    markup.sundown_markdown:
        class: Vendor\QuoteBundle\Markup\Sundown
    # ...

n1c0_quote:
    # ...
    service:
        markup: markup.sundown_markdown
    # ...

另一个例子,使用 Pandoc 作为标记服务

Pandoc 是一个 Haskell 程序,允许您将文档从一种格式转换为另一种格式。更多信息请参见 Pandoc

要安装 Pandoc,请运行以下命令

$ apt-get install pandoc

有关 Pandoc 安装的更多信息,请参阅 Pandoc 安装

我们需要一个简单的 PHP 包装器。推荐使用 composer 安装 Pandoc PHP。

{
    "require": {
        "ryakad/pandoc-php": "dev-master"
    }
}

安装完毕后,您可以创建一个类似以下的服务标记

<?php

namespace vendor\QuoteBundle\Markup;

use N1c0\QuoteBundle\Markup\ParserInterface;
use Pandoc\Pandoc;

class MarkupPandoc implements ParserInterface
{
    private $parser;

    protected function getParser()
    {
        if (null === $this->parser) {
            $this->parser = new Pandoc();        
        }

        return $this->parser;
    }

    public function parse($raw)
    {
        return $this->getParser()->convert($raw, "markdown", "html");
    }
}

以及用于启用此解析器桥梁的服务定义

# app/config/config.yml

services:
    # ...
    markup.pandoc_markdown:
        class: Vendor\QuoteBundle\Markup\MarkupPandoc
    # ...

n1c0_quote:
    # ...
    service:
        markup: markup.pandoc_markdown
    # ...

FOSCommentBundle 的集成

src/MyProject/MyBundle/Resources/views/Quote/getQuotes.html.twig 中添加

<a href="{{ path('api_1_get_quote_thread', {'id': quote.id}) }}">Commentaires</a>

作为附加内容的文档(NelmioApiDocBundle)

访问 https://:8000/api/doc