Skip to content

Instantly share code, notes, and snippets.

@77web
Created July 10, 2014 14:01
Show Gist options
  • Save 77web/9584fc992310b1c96514 to your computer and use it in GitHub Desktop.
Save 77web/9584fc992310b1c96514 to your computer and use it in GitHub Desktop.
BEAR.SundayでDoctrine2のORMを使ってみた ref: http://qiita.com/77web@github/items/7b67e490ac59dcab0ca8
composer create-project bear/skeleton My.NoteApp
cd My.NoteApp
composer install
// src/Resource/App/Note.php
namespace My\NoteApp\Resource\App;
use BEAR\Resource\ResourceObject;
class Note extends ResourceObject
{
public function onGet($id)
{
$note = $this->entityManager->find('...', $id);
$this['note'] = ['body' => $note->getBody()];
return $this;
}
}
// src/Module/Provider/DoctrineORMProvider
namespace My\NoteApp\Module\Provider;
use Doctrine\ORM\Tools\Setup;
use Doctrine\ORM\EntityManager;
use Ray\Di\ProviderInterface;
use BEAR\Sunday\Inject\AppDirInject;
class DoctrineORMProvider implements ProviderInterface
{
use AppDirInject;
public function get()
{
$config = Setup::createAnnotationMetadataConfiguration(array(__DIR__."/../Entity"), false);
$conn = array(
'driver' => 'pdo_sqlite',
'path' => $this->appDir . '/var/db/db.sqlite',
);
$entityManager = EntityManager::create($conn, $config);
return $entityManager;
}
}
// src/Module/AppModule.php
protected function configure()
{
$this->install(...); // 最初から書いてある部分
$this->bind('Doctrine\ORM\EntityManager')->toProvider('My\NoteApp\Module\Provider\DoctrineORMProvider'); // bind,toProviderともに最初のバックスラッシュは要らなかった
}
// src/Entity/Note.php
namespace My\NoteApp\Entity;
/**
* @Entity
* @Table(name="note")
*/
class Note
{
/**
* @var int
* @Id
* @Column(type="integer")
* @GeneratedValue
*/
private $id;
/**
* @var string
* @Column(type="text")
*/
private $body;
// getter,setterは省略
}
sqlite3 var/db/db.sqlite
> create table note(id INTEGER PRIMARY AUTOINCREMENT NOT NULL, body TEXT NULL);
> insert into note(body) values('test body1');
> insert into note(body) values('test body2');
> .exit
// src/Resource/App/Note.php
namespace My\NoteApp\Resource\App;
use BEAR\Resource\ResourceObject;
use Doctrine\ORM\EntityManager;
use Ray\Di\Di\Inject;
class Note extends ResourceObject
{
/**
* @var EntityManager
*/
private $entityManager;
/**
* @param EntityManager $entityManager
* @Inject
*/
public function __construct(EntityManager $entityManager)
{
$this->entityManager = $entityManager;
}
public function onGet($id)
{
$note = $this->entityManager->find('\My\NoteApp\Entity\Note', $id);
$this['note'] = ['body' => $note->getBody()];
return $this;
}
}
php bootstrap/contexts/api.php get 'app://self/note?id=1'
[BODY]
note => array(
body test body1
),
[VIEW]
{
"note": {
"body": "test body1"
},
"_links": {
"self": {
"href": "http://localhost/app/note/?id=1"
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment