Skip to content
This repository has been archived by the owner on Nov 15, 2022. It is now read-only.

Implementando migrations #76

Open
wants to merge 10 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,4 @@ config/config.php
composer.lock
nbproject
.idea
orcamentos_diagram.asta.bak
97 changes: 77 additions & 20 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,26 +2,29 @@

### Configure o Apache VirtualHost

<VirtualHost *:80>
DocumentRoot "<sua pasta de projetos>/<nome escolhido ao clonar>" #ver instruções abaixo
ServerName orcamentos.dev

<Directory "<sua pasta de projetos>/<nome escolhido ao clonar>">
Options Indexes Multiviews FollowSymLinks
AllowOverride All
Order allow,deny
Allow from all


RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule !\.(js|ico|gif|jpg|png|css|htm|html|txt|mp3)$ index.php
</Directory>
</VirtualHost>
```apache
<VirtualHost *:80>
DocumentRoot "<sua pasta de projetos>/<nome escolhido ao clonar>" #ver instruções abaixo
ServerName orcamentos.dev

<Directory "<sua pasta de projetos>/<nome escolhido ao clonar>">
Options Indexes Multiviews FollowSymLinks
AllowOverride All
Order allow,deny
Allow from all

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule !\.(js|ico|gif|jpg|png|css|htm|html|txt|mp3)$ index.php
</Directory>
</VirtualHost>
```

É preciso criar o alias para o endereço _orcamentos.dev_ no seu /etc/hosts (Linux ou Mac)

`127.0.0.1 orcamentos.dev`
```ini
127.0.0.1 orcamentos.dev
```

Para criação de um virtual host no **Windows**, siga as instruções encontradas [neste link](http://www.emersoncarvalho.com/web/configurando-virtual-hosts-no-windows/).

Expand All @@ -33,11 +36,41 @@ Através da linha de comando, acessar sua pasta de projetos e clonar com `git cl

Acessar a pasta criada `cd <nome da pasta do projeto>` e atualizar o Composer fornecido:

`php composer.phar self-update`
```bash
$ php composer.phar self-update
```

Instalar as dependências do projeto:

`php composer.phar update`
```bash
$ php composer.phar update
```

### Linhas de comando

Para facilicar algumas tarefas do projeto foi criado uma interface de linha de comando que pode ser executada de duas formas:

```bash
$ ./bin/orcamentos
```

ou

```bash
$ php bin/orcamentos.php
```

Executando o comando acima será exibido os comandos disponiveis, para executar algum comando disponível basta exectuar:

```bash
$ ./bin/orcamentos comando
```

ou

```bash
$ php bin/orcamentos.php comando
```

### Configuração

Expand All @@ -47,7 +80,31 @@ Basta duplicar o arquivo `config/config.php.sample` para `config/config.php` e m

O projeto usa o Doctrine, então é preciso criar a base de dados (de acordo com as configurações do config.php) e executar:

`./bin/orcamentos orcamentos:initialize`
```bash
$ ./bin/orcamentos orcamentos:initialize
```

**OBS:** O comando acima deve ser executado apenas para criação do projeto.

### Atualizando banco de dados

Para facilitar a evolução do banco foi utilizado [Doctrine Migrations](http://www.doctrine-project.org/projects/migrations.html) uma ferramenta de versionamento para banco de dados.

Para efetuar qualquer alteração no banco de dados, basta criar e/ou alterar e/ou remover qualquer atributos e/ou entidade presente na pasta `src/Orcamentos/Model` e executar:

```bash
$ ./bin/orcamentos migrations:diff
```

Esse comanda irá comprar os mapeamentos com banco configura e gerar um novo arquivo em `src/Orcamentos/Migrations` com essas alterações.

Para aplicar as diferenças ao banco basta executar:

```bash
$ ./bin/orcamentos migrations:migrate
```

Para outros comandos ou dúvida basta acessar a documentação do [Doctrine Migrations](http://www.doctrine-project.org/projects/migrations.html).

### Exemplo de uso

Expand Down
15 changes: 1 addition & 14 deletions bin/orcamentos
Original file line number Diff line number Diff line change
@@ -1,17 +1,4 @@
#!/usr/bin/env php
<?php

use Symfony\Component\Console\Application as ConsoleApplication;
use Doctrine\ORM\Tools\Console\ConsoleRunner;

chdir(__DIR__ . '/..');

require_once('vendor/autoload.php');
$application = new ConsoleApplication();
$application->setHelperSet(include 'cli-config.php');
$application->add(new Orcamentos\Console\InitializeCommand);
$application->add(new Orcamentos\Console\ResetPasswordCommand);

ConsoleRunner::addCommands($application);

$application->run();
include "orcamentos.php";
90 changes: 90 additions & 0 deletions bin/orcamentos.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
<?php

use Doctrine\Common\Annotations\AnnotationRegistry;
use Doctrine\DBAL\Tools\Console\Helper\ConnectionHelper;
use Doctrine\ORM\Configuration;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\Tools\Console\Helper\EntityManagerHelper;
use Symfony\Component\Console\Application as ConsoleApplication;
use Symfony\Component\Console\Helper\DebugFormatterHelper;
use Symfony\Component\Console\Helper\FormatterHelper;
use Symfony\Component\Console\Helper\HelperSet;
use Symfony\Component\Console\Helper\ProcessHelper;
use Symfony\Component\Console\Helper\QuestionHelper;

chdir(__DIR__ . '/..');

define('DS', DIRECTORY_SEPARATOR);

require 'vendor/autoload.php';

// Load configs
$configValues = require_once 'config/config.php';

// Mapping annotation
AnnotationRegistry::registerFile('vendor' . DS . 'doctrine' . DS . 'orm' . DS . 'lib' . DS . 'Doctrine' . DS . 'ORM' . DS . 'Mapping' . DS . 'Driver' . DS . 'DoctrineAnnotations.php');

// Doctrine AnnotationDriver
$driver = new Doctrine\ORM\Mapping\Driver\AnnotationDriver(
new Doctrine\Common\Annotations\AnnotationReader(),
array('src' . DS . 'Orcamentos' . DS . 'Model')
);

// Doctrine cache
$configCache = ucwords(strtolower($configValues['db.options']['cache']));
$cache = new \ReflectionClass("\\Doctrine\\Common\\Cache\\{$configCache}Cache");

// Doctrine
$config = new Configuration();

// Proxies (3)
$config->setProxyDir(sys_get_temp_dir() . '/' . md5(__DIR__));
$config->setProxyNamespace('Proxies');
$config->setAutoGenerateProxyClasses(true);
$config->setMetadataDriverImpl($driver);
$config->setMetadataCacheImpl($cache->newInstance());

// EntityManager
$em = EntityManager::create($configValues['db.options'], $config);

// Console
$console = new ConsoleApplication('Gerenciamento de Orçamentos', '1.0.0');
$console->setCatchExceptions(true);
$console->setHelperSet(new HelperSet([
'db' => new ConnectionHelper($em->getConnection()),
'em' => new EntityManagerHelper($em),
'dialog' => $console->getHelperSet()->get('dialog'),
'progress' => $console->getHelperSet()->get('progress'),
'table' => $console->getHelperSet()->get('table'),
new FormatterHelper(),
new DebugFormatterHelper(),
new ProcessHelper(),
new QuestionHelper()
]));

$console->addCommands(array(
// ORM Commands
new \Doctrine\ORM\Tools\Console\Command\ClearCache\MetadataCommand(),
new \Doctrine\ORM\Tools\Console\Command\ClearCache\ResultCommand(),
new \Doctrine\ORM\Tools\Console\Command\ClearCache\QueryCommand(),
new \Doctrine\ORM\Tools\Console\Command\EnsureProductionSettingsCommand(),
new \Doctrine\ORM\Tools\Console\Command\ConvertDoctrine1SchemaCommand(),
new \Doctrine\ORM\Tools\Console\Command\GenerateRepositoriesCommand(),
new \Doctrine\ORM\Tools\Console\Command\GenerateEntitiesCommand(),
new \Doctrine\ORM\Tools\Console\Command\GenerateProxiesCommand(),
new \Doctrine\ORM\Tools\Console\Command\ConvertMappingCommand(),

// Migrations Commands
new \Doctrine\DBAL\Migrations\Tools\Console\Command\DiffCommand(),
new \Doctrine\DBAL\Migrations\Tools\Console\Command\ExecuteCommand(),
new \Doctrine\DBAL\Migrations\Tools\Console\Command\GenerateCommand(),
new \Doctrine\DBAL\Migrations\Tools\Console\Command\LatestCommand(),
new \Doctrine\DBAL\Migrations\Tools\Console\Command\MigrateCommand(),
new \Doctrine\DBAL\Migrations\Tools\Console\Command\StatusCommand(),
new \Doctrine\DBAL\Migrations\Tools\Console\Command\VersionCommand(),

// Orcamentos Commands
new Orcamentos\Console\InitializeCommand(),
new Orcamentos\Console\ResetPasswordCommand()
));
$console->run();
56 changes: 0 additions & 56 deletions cli-config.php

This file was deleted.

59 changes: 30 additions & 29 deletions composer.json
Original file line number Diff line number Diff line change
@@ -1,31 +1,32 @@
{
"name": "eminetto/silex-sample",
"description": "Silex sample",
"require": {
"php": ">=5.3.3",
"silex/silex": "1.0.*",
"symfony/http-kernel": "*",
"symfony/browser-kit": "*",
"symfony/console": "*",
"doctrine/dbal": "*",
"doctrine/orm": "*",
"twig/twig": ">=1.8,<2.0-dev",
"intervention/image": "dev-master",
"symfony/twig-bridge": "2.1.*",
"swiftmailer/swiftmailer": ">=4.1.2,<4.2-dev",
"dflydev/doctrine-orm-service-provider": "1.0.*@dev",
"zendframework/zend-crypt": "*",
"pagerfanta/pagerfanta": "1.0.*@dev"
},
"require-dev": {
"sebastian/phpcpd": "*",
"phpunit/phpunit": "*",
"mockery/mockery": "dev-master@dev"
},
"minimum-stability": "dev",
"autoload": {
"psr-0": {
"Orcamentos\\": "src/"
}
}
"name": "coderockr/orcamentos",
"description": "Aplicativo de gerenciamento de Orçamentos",
"require": {
"php": ">=5.3.3",
"silex/silex": "1.0.*",
"symfony/http-kernel": "*",
"symfony/browser-kit": "*",
"symfony/console": "*",
"doctrine/dbal": "*",
"doctrine/orm": "*",
"doctrine/migrations": "1.0.*@dev",
"dflydev/doctrine-orm-service-provider": "1.0.*@dev",
"twig/twig": ">=1.8,<2.0-dev",
"symfony/twig-bridge": "2.1.*",
"intervention/image": "dev-master",
"swiftmailer/swiftmailer": ">=4.1.2,<4.2-dev",
"zendframework/zend-crypt": "*",
"pagerfanta/pagerfanta": "1.0.*@dev"
},
"require-dev": {
"phpunit/phpunit": "*",
"mockery/mockery": "dev-master@dev",
"sebastian/phpcpd": "*"
},
"autoload": {
"psr-4": {
"Orcamentos\\": "src/Orcamentos"
}
},
"minimum-stability": "dev"
}
Binary file modified composer.phar
Binary file not shown.
Loading