DWX2015 Code Generierung

Ralf Eggert
Ralf EggertGeschäftsführer / Gründer at Travello GmbH
Code-GenerierungCode-Generierung
Mit der Konsole

Repository: https://github.com/RalfEggert/dwx2015-code-generierung
Slides: http://de.slideshare.net/eggertralf/dwx2015-codegenerierung
1 / 59
Über michÜber mich
2 / 59www.RalfEggert.dewww.RalfEggert.de
[B01]
MotivationMotivation
3 / 59
Frage ans PublikumFrage ans Publikum
4 / 59
[b02][b02]
Einsatzzwecke: KonsoleEinsatzzwecke: Konsole
5 / 59
Codegenerierung
DeploymentSkripte
InstallationsSkripte
Datenbank Migration
SocketServerCron Jobs
Spider / Crawler
[B03]
ToolsTools
6 / 59
Tools Konsole & CodeTools Konsole & Code
7 / 59
Konsole Code
Tools Konsole & CodeTools Konsole & Code
8 / 59
Konsole Code
VariantenVarianten
9 / 59
Zend Framework 2
Full-Stack ZF2 Applikation
Mit MVC
Gute ZF2-Kenntnisse
ZendCodeGenerator
ZendConsole
ZFConsole
»Richtige« Konsolen-Anwendung
Ohne MVC
Wenige ZF2-Kenntnisse
ZendCodeGenerator
ZendConsole
VariantenVarianten
10 / 59
Zend Framework 2
Full-Stack ZF2 Applikation
Mit MVC
Gute ZF2-Kenntnisse
ZendCodeGenerator
ZendConsole
ZFConsole
»Richtige« Konsolen-Anwendung
Ohne MVC
Wenige ZF2-Kenntnisse
ZendCodeGenerator
ZendConsole
???
BausteineBausteine
11 / 59
PHP 5.5
C0mposer
ZFConsole
ZendConsole
ZendCode
ZendConfig
ZendDb
ZendFilter
ZendValidator
Composer.jsonComposer.json
12 / 59
{
"name": "ralfeggert/dwx2015-code-generierung",
"description": "DWX2015: Tool zur Code-Generierung",
"license": "MIT",
"require": {
"php": ">=5.5",
"zfcampus/zf-console": "~1.0",
"zendframework/zend-code": "~2.5",
"zendframework/zend-config": "~2.5",
"zendframework/zend-console": "~2.5",
"zendframework/zend-db": "~2.5",
"zendframework/zend-filter": "~2.5",
"zendframework/zend-validator": "~2.5"
},
"autoload": {
"psr-4": {
"PHPCG": "src/PHPCG"
}
},
"bin": ["bin/phpcg.php"]
}
InstallationInstallation
13 / 59
// Projekt klonen
$ cd /home/devhost/
$ git clone https://github.com/RalfEggert/dwx2015-code-generierung
$ cd dwx2015-code-generierung/
// Abhängigkeiten per Composer installieren
$ php composer.phar install
// PHP Code Generator ausführen
$ bin/phpcg.php
[B00]
ZFConsoleZFConsole
14 / 59
ProjektProjekt
https://github.com/zfcampus/zf-console 15 / 59
[b00]
ApplicationApplication
16 / 59
<?php
// Datei /bin/phpcg.php
use ZendConsoleConsole;
use ZFConsoleApplication;
define('DWX2015_PHPCG_ROOT', __DIR__ . '/..');
define('VERSION', '1.0.0');
include DWX2015_PHPCG_ROOT . '/vendor/autoload.php';
$routes = include DWX2015_PHPCG_ROOT . '/config/routes.php';
$console = Console::getInstance();
$application = new Application(
'PHP Code Generator (DWX2015)', VERSION, $routes, $console
);
$exit = $application->run();
exit($exit);
AutovervollständigungAutovervollständigung
17 / 59
// Autovervollständigung einrichten
$ sudo bin/phpcg.php autocomplete > /etc/bash_completion.d/phpcg.php.sh
$ source /etc/bash_completion.d/phpcg.php.sh
// Autovervollständigung nutzen
$ bin/phpcg.php <TAB>
autocomplete create-hello-you-class create-user-entities
hello-someone hello-world hello-you
update-user-entities help version
PHAR GenerierenPHAR Generieren
18 / 59
// PHAR Paket erstellen lassen
$ bin/create-phar.php
Phar created successfully in /home/devhost/dwx2015-code-generate/phpcg.phar
// Phar Paket verwenden
$ php phpcg.phar
---------------------------------------------------------------------------
PHP Code Generator (DWX2015), version 1.0.0
Available commands:
autocomplete Command autocompletion setup
create-hello-you-class Create hello you class
create-user-entities Create user entities
hello-someone Hello someone
hello-world Hello world
hello-you Hello you
help Get help for individual commands
update-user-entities Update user entities
version Display the version of the script
---------------------------------------------------------------------------
HilfeHilfe
19 / 59
// Autovervollständigung einrichten
$ bin/phpcg.php help
---------------------------------------------------------------------------
PHP Code Generator (DWX2015), version 1.0.0
Available commands:
autocomplete Command autocompletion setup
create-hello-you-class Create hello you class
create-user-entities Create user entities
hello-someone Hello someone
hello-world Hello world
hello-you Hello you
help Get help for individual commands
update-user-entities Update user entities
version Display the version of the script
---------------------------------------------------------------------------
Routing BeispieleRouting Beispiele
20 / 59
// Route ohne Parameter 'say-stuff'
$ bin/phpcg.php say-stuff
// Route mit obligatorischem Wertparameter 'say-stuff <stuff>'
$ bin/phpcg.php say-stuff Whatever
// Route mit optionalem Flag 'do-stuff [--strict|-s]:strict'
$ bin/phpcg.php do-stuff -s
// Route mit optionalem Wertparameter 'do-stuff [--target=]'
$ bin/phpcg.php do-stuff --target=Whatever
[B04]
KommandosKommandos
21 / 59
RouteRoute
22 / 59
<?php
// Datei /config/routes.php
return array(
array(
'name' => 'hello-world',
'route' => 'hello-world',
'description' => 'Say hello to the world',
'short_description' => 'Hello world',
'handler' => 'PHPCGCommandHelloWorld',
),
[...]
);
KommandoKommando
23 / 59
<?php
// Datei /src/PHPCG/Command/HelloWorld.php
namespace PHPCGCommand;
use ZendConsoleAdapterAdapterInterface as Console;
use ZendConsoleColorInterface as Color;
use ZFConsoleRoute;
class HelloWorld
{
public function __invoke(Route $route, Console $console)
{
$console->writeLine('Hello World', Color::YELLOW);
}
}
KonsoleKonsole
24 / 59
$ bin/phpcg.php hello-world
---------------------------------------------------------------------------
PHP Code Generator (DWX2015), version 1.0.0
Hello World
---------------------------------------------------------------------------
RouteRoute
25 / 59
<?php
// Datei /config/routes.php
return array(
array(
'name' => 'hello-you',
'route' => 'hello-you <you>',
'description' => 'Say hello to you',
'short_description' => 'Hello you',
'options_descriptions' => array(
'<you>' => 'Your name'
),
'handler' => 'PHPCGCommandHelloYou',
),
[...]
);
KommandoKommando
26 / 59
<?php
// Datei /src/PHPCG/Command/HelloYou.php
namespace PHPCGCommand;
use ZendConsoleAdapterAdapterInterface as Console;
use ZendConsoleColorInterface as Color;
use ZFConsoleRoute;
class HelloYou
{
public function __invoke(Route $route, Console $console)
{
$you = $route->getMatchedParam('you');
$console->write('Hello ');
$console->write(sprintf('"%s"', $you), Color::YELLOW);
$console->writeLine(' ...');
}
}
KonsoleKonsole
27 / 59
$ bin/phpcg.php hello-you Ralf
---------------------------------------------------------------------------
PHP Code Generator (DWX2015), version 1.0.0
Hello "Ralf" ...
---------------------------------------------------------------------------
RouteRoute
28 / 59
<?php
// Datei /config/routes.php
return array(
array(
'name' => 'hello-someone',
'route' => 'hello-someone',
'description' => 'Say hello to someone',
'short_description' => 'Hello someone',
'handler' => 'PHPCGCommandHelloSomeOne',
),
[...]
);
KommandoKommando
29 / 59
<?php
// Datei /src/PHPCG/Command/HelloSomeOne.php
[...]
use ZendConsolePromptLine;
use ZendConsolePromptSelect;
class HelloSomeOne
{
public function __invoke(Route $route, Console $console)
{
$prompt = new Line('Please enter any name: ');
$you = $prompt->show();
$options = array(Color::BLACK => 'BLACK', [...], Color::BLUE => 'BLUE');
$prompt = new Select('Please choose any color: ', $options);
$color = $prompt->show();
$console->write('Hello ');
$console->write(sprintf(' %s ', $you), Color::WHITE, $color);
$console->writeLine(' ...');
}
}
KonsoleKonsole
30 / 59
$ bin/phpcg.php hello-someone
---------------------------------------------------------------------------
PHP Code Generator (DWX2015), version 1.0.0
Please enter any name: Ralf
Please choose any color:
1) BLACK
2) RED
3) GREEN
4) YELLOW
5) BLUE
Hello ...
---------------------------------------------------------------------------
ralf@ralf-HP-2013:/home/devhost/dwx2015-code-generierung$
Ralf
[B05]
CODECODE
GeneratorGenerator
31 / 59
ProjektProjekt
https://github.com/zendframework/zend-code 32 / 59
[b00]
GeneratorenGeneratoren
33 / 59
Body Generator
Class Generator
Doc Block Generator
FileGenerator
Method Generator
Parameter Generator
PropertyGenerator
TRAIT Generator
Value Generator
Weitere Generatoren
RouteRoute
34 / 59
<?php
// Datei /config/routes.php
return array(
array(
'name' => 'create-hello-you-class',
'route' => 'create-hello-you-class',
'description' => 'Create a hello you class',
'short_description' => 'Create hello you class',
'handler' => 'PHPCGCommandCreateHelloYou',
),
[...]
);
Class Generator IClass Generator I
35 / 59
<?php
// Datei /src/PHPCG/Generator/HelloYouClassGenerator.php
namespace PHPCGGenerator;
use ZendCodeGeneratorClassGenerator;
use ZendCodeGeneratorMethodGenerator;
use ZendCodeGeneratorParameterGenerator;
use ZendCodeGeneratorPropertyGenerator;
class HelloYouClassGenerator
{
private $class;
public function getClass()
{
return $this->class;
}
public function createClass() {}
}
Class Generator IIClass Generator II
36 / 59
<?php
public function createClass()
{
$nameProperty = new PropertyGenerator('name');
$nameProperty->addFlag(PropertyGenerator::FLAG_PRIVATE);
$nameSetMethod = new MethodGenerator('setName');
$nameSetMethod->addFlag(MethodGenerator::FLAG_PUBLIC);
$nameSetMethod->setParameter(new ParameterGenerator('name'));
$nameSetMethod->setBody('$this->name = $name;');
$greetMethod = new MethodGenerator('greet');
$greetMethod->addFlag(MethodGenerator::FLAG_PUBLIC);
$greetMethod->setBody('return sprintf("Hello %s!", $this->name);');
$this->class = new ClassGenerator('HelloYou', 'HelloGreeting');
$this->class->addPropertyFromGenerator($nameProperty);
$this->class->addMethods(array($nameSetMethod, $greetMethod));
}
FILE GeneratorFILE Generator
37 / 59
<?php
// Datei /src/PHPCG/Generator/ClassFileGenerator.php
namespace PHPCGGenerator;
use ZendCodeGeneratorClassGenerator;
use ZendCodeGeneratorDocBlockGenerator;
use ZendCodeGeneratorFileGenerator;
class ClassFileGenerator
{
private $file;
public function getFile()
{
return $this->file;
}
public function createFile(ClassGenerator $class)
{
$docBlock = new DocBlockGenerator([...]);
$this->file = new FileGenerator();
$this->file->setClass($class);
$this->file->setDocBlock($docBlock);
}
}
KommandoKommando
38 / 59
<?php
// Datei /src/PHPCG/Command/CreateHelloYouClass.php
namespace PHPCGCommand;
[...]
class CreateHelloYouClass
{
public function __invoke(Route $route, Console $console)
{
$fileName = DWX2015_PHPCG_ROOT . '/tmp/HelloYouClass.php';
$classGenerator = new HelloYouClassGenerator();
$classGenerator->createClass();
$class = $classGenerator->getClass();
$fileGenerator = new ClassFileGenerator();
$fileGenerator->createFile($class);
$file = $fileGenerator->getFile();
file_put_contents($fileName, $file->generate());
[...]
}
}
KonsoleKonsole
39 / 59
$ bin/phpcg.php create-hello-you-class
----------------------------------------------------------------------------------------
PHP Code Generator (DWX2015), version 1.0.0
Created class HelloYou in file
/home/devhost/dwx2015-code-generierung/tmp/HelloYouClass.php
<?php
namespace HelloGreeting;
class HelloYou
{
private $name = null;
public function setName($name)
{
$this->name = $name;
}
public function greet()
{
return sprintf("Hello %s!", $this->name);
}
}
----------------------------------------------------------------------------------------
[B06]
DatenbankDatenbank
40 / 59
ProjektProjekt
https://github.com/zendframework/zend-db 41 / 59
[b00]
ZendDb KomponentenZendDb Komponenten
42 / 59
Adapter
Metadata
Result Set
RowGateway
SQL
Table Gateway
DatenbankmodellDatenbankmodell
43 / 59
DB KonfigurationDB Konfiguration
44 / 59
<?php
// Datei /config/db.php
return array(
'adapter' => array(
'driver' => 'Pdo',
'dsn' => 'mysql:dbname=dwx2015.user;host=localhost;charset=utf8',
'user' => 'dwx2015',
'pass' => 'dwx2015',
),
);
Meta Data Collector IMeta Data Collector I
45 / 59
<?php
// Datei /src/PHPCG/MetaData/Collector.php
namespace PHPCGCollector;
use ZendDbMetadataMetadata;
use ZendDbMetadataObjectColumnObject;
class MetaDataCollector
{
public function __construct(Metadata $metaData)
{
$this->metaData = $metaData;
}
public function fetchTableColumns($tableName)
{
$tableColumns = array();
[...]
return $tableColumns;
}
}
Meta Data Collector IIMeta Data Collector II
46 / 59
<?php
[...]
foreach ($tableMeta->getColumns() as $column) {
$config = array('required' => !$column->getIsNullable());
if (in_array($column->getDataType(), array('varchar','text','enum'))) {
$config['type'] = 'string';
} else {
$config['type'] = 'integer';
}
if ($column->getDataType() == 'varchar') {
$config['max_length'] = $column->getCharacterMaximumLength();
} elseif ($column->getDataType() == 'enum') {
$config['values'] = $column->getErrata('permitted_values');
}
$tableColumns[$column->getName()] = $config;
}
User Entity Generator IUser Entity Generator I
47 / 59
<?php
// Datei /src/PHPCG/Generator/UserEntityGenerator.php
namespace PHPCGGenerator;
use ZendCodeGeneratorClassGenerator;
use ZendCodeGeneratorDocBlockGenerator;
use ZendCodeGeneratorMethodGenerator;
use ZendCodeGeneratorParameterGenerator;
use ZendCodeGeneratorPropertyGenerator;
use ZendCodeGeneratorValueGenerator;
use ZendFilterWordUnderscoreToCamelCase;
class UserEntityGenerator extends ClassGenerator
{
private $class;
private $filterUTCC;
public function __construct() {}
public function getClass() {}
public function createClass() {}
public function addEntityProperties(array $columns = array()) {}
}
User Entity Generator IIUser Entity Generator II
48 / 59
<?php
public function __construct()
{
$this->filterUTCC = new UnderscoreToCamelCase();
}
public function getClass()
{
return $this->class;
}
public function createClass()
{
$this->class = new ClassGenerator('UserEntity', 'UserEntity');
$this->class->setDocBlock(
new DocBlockGenerator([...])
);
}
User Entity Generator IIIUser Entity Generator III
49 / 59
<?php
public function addEntityProperties()
{
foreach ($this->columns as $name => $attributes) {
$property = $this->generateProperty($name, $attributes);
$getMethod = $this->generateGetMethod($name, $attributes);
$setMethod = $this->generateSetMethod($name, $attributes);
$this->class->addPropertyFromGenerator($property);
$this->class->addMethodFromGenerator($getMethod);
$this->class->addMethodFromGenerator($setMethod);
}
}
private function generateProperty($name, array $attributes = array())
{
$property = new PropertyGenerator($name);
$property->addFlag(PropertyGenerator::FLAG_PROTECTED);
return $property;
}
User Entity Generator IVUser Entity Generator IV
50 / 59
<?php
private function generateGetMethod($name, array $attributes = array())
{
$methodName = 'get' . $this->filterUTCC->filter($name);
$getMethod = new MethodGenerator($methodName);
$getMethod->addFlag(MethodGenerator::FLAG_PUBLIC);
$getMethod->setBody('return $this->' . $name . ';');
return $getMethod;
}
User Entity Generator VUser Entity Generator V
51 / 59
<?php
private function generateSetMethod($name, array $attribs = array())
{
$methodName = 'set' . $this->filterUTCC->filter($name);
$defaultValue = !$attribs['required'] ? new ValueGenerator(null) : null;
$setMethod = new MethodGenerator($methodName);
$setMethod->addFlag(MethodGenerator::FLAG_PUBLIC);
$setMethod->setParameter(
new ParameterGenerator($name, null, $defaultValue)
);
$setMethod->setBody('$this->' . $name . ' = $' . $name . ';');
return $setMethod;
}
Kommando IKommando I
52 / 59
<?php
// Datei /src/PHPCG/Command/CreateUserEntities.php
namespace PHPCGCommand;
use PHPCGCollectorMetaDataCollector;
use PHPCGGeneratorClassFileGenerator;
use PHPCGGeneratorUserEntityGenerator;
use ZendConsoleAdapterAdapterInterface as Console;
use ZendConsoleColorInterface as Color;
use ZendDbAdapterAdapter;
use ZendDbMetadataMetadata;
use ZFConsoleRoute;
class CreateUserEntities
{
public function __invoke(Route $route, Console $console)
{
[...]
}
}
Kommando IIKommando II
53 / 59
<?php
public function __invoke(Route $route, Console $console)
{
$dbConfig = include DWX2015_PHPCG_ROOT . '/config/db.php';
$fileName = DWX2015_PHPCG_ROOT . '/tmp/UserEntity.php';
$dbAdapter = new Adapter($dbConfig['adapter']);
$metaData = new Metadata($dbAdapter);
$collector = new MetaDataCollector($metaData);
$userColumns = $collector->fetchTableColumns('user');
$classGenerator = new UserEntityGenerator();
$classGenerator->createClass();
$classGenerator->addEntityProperties($userColumns);
$class = $classGenerator->getClass();
$fileGenerator = new ClassFileGenerator();
$fileGenerator->createFile($class);
$file = $fileGenerator->getFile();
file_put_contents($fileName, $file->generate());
[...]
}
KonsoleKonsole
54 / 59
$ bin/phpcg.php create-user-entities
-------------------------------------------------------------------------------------------------
PHP Code Generator (DWX2015), version 1.0.0
Created class UserEntity in file
/home/devhost/dwx2015-code-generierung/tmp/UserEntity.php
<?php
namespace UserEntity;
class UserEntity
{
protected $id = null;
[...]
public function getId()
{
return $this->id;
}
public function setId($id)
{
$this->id = $id;
}
[...]
}
-------------------------------------------------------------------------------------------------
[B07]
War es das?War es das?
55 / 59
Weitere IdeenWeitere Ideen
56 / 59
Entities
Aktualisieren
✓
Formulare
generieren
Validierung
In Entity
✓
Entities
löschen
InputFilter
Generieren
Fragen vom Publikum?Fragen vom Publikum?
57 / 59
[b08]
DANKEDANKE
Für Ihre / Eure Aufmerksamkeit!

Repository: https://github.com/RalfEggert/dwx2015-code-generierung
Slides: http://de.slideshare.net/eggertralf/dwx2015-codegenerierung
58 / 59
BildnachweisBildnachweis
[B00] Fotos von Ralf Eggert
[B01] Carrot And Stick Incentives Lead Manage http://www.workcompass.com/ von Alan O'Rourke - CC-BY https://creativecommons.org/licenses/by/2.0/
[B02] Frontiers 2011 - Day 2 https://www.flickr.com/photos/frontiersofinteraction/5866676276/ von Frontiersofinteraction - CC-BY https://creativecommons.org/licenses/by/2.0/
[B03] Multi Tools https://www.flickr.com/photos/pennuja/5363515039 von Jim Pennucci - CC-BY https://creativecommons.org/licenses/by/2.0/
[B04] Command https://www.flickr.com/photos/shearforce/3838603833/ von Margaret Shear - CC-BY-SA https://creativecommons.org/licenses/by-sa/2.0/
[B05] Propeller Generator in the Sunset https://www.flickr.com/photos/jiazi/2060352110/ von Tim Wang - CC-BY-SA https://creativecommons.org/licenses/by-sa/2.0/
[B06] Fixing the database https://www.flickr.com/photos/dahlstroms/4140461901 von Håkan Dahlström - CC-BY https://creativecommons.org/licenses/by/2.0/
[B07] I have an idea @ home https://www.flickr.com/photos/ful1to/3783198574/ von Julian Santacruz - CC-BY https://creativecommons.org/licenses/by/2.0/
[B08] Etech05: Audience https://www.flickr.com/photos/oreilly/6648470 von James Duncan Davidson - CC-BY https://creativecommons.org/licenses/by/2.0/
Alle weiteren Screenshots wurden von Ralf Eggert erstellt.
59 / 59
1 of 59

Recommended

Zend\Expressive - höher, schneller, weiter by
Zend\Expressive - höher, schneller, weiterZend\Expressive - höher, schneller, weiter
Zend\Expressive - höher, schneller, weiterRalf Eggert
2.2K views50 slides
DevOps in PHP environment by
DevOps in PHP environment DevOps in PHP environment
DevOps in PHP environment Evaldo Felipe
160 views94 slides
Composer for busy developers - DPC13 by
Composer for busy developers - DPC13Composer for busy developers - DPC13
Composer for busy developers - DPC13Rafael Dohms
5.4K views141 slides
Designing High Performance RTC Signaling Servers by
Designing High Performance RTC Signaling ServersDesigning High Performance RTC Signaling Servers
Designing High Performance RTC Signaling ServersDaniel-Constantin Mierla
542 views27 slides
Kicking off with Zend Expressive and Doctrine ORM (PHPNW2016) by
Kicking off with Zend Expressive and Doctrine ORM (PHPNW2016)Kicking off with Zend Expressive and Doctrine ORM (PHPNW2016)
Kicking off with Zend Expressive and Doctrine ORM (PHPNW2016)James Titcumb
1.3K views78 slides
Artificial Neural Network in a Tic Tac Toe Symfony Console Application - Symf... by
Artificial Neural Network in a Tic Tac Toe Symfony Console Application - Symf...Artificial Neural Network in a Tic Tac Toe Symfony Console Application - Symf...
Artificial Neural Network in a Tic Tac Toe Symfony Console Application - Symf...aferrandini
3K views57 slides

More Related Content

Similar to DWX2015 Code Generierung

PHP QA Tools by
PHP QA ToolsPHP QA Tools
PHP QA Toolsrjsmelo
2.1K views21 slides
The why and how of moving to PHP 5.5/5.6 by
The why and how of moving to PHP 5.5/5.6The why and how of moving to PHP 5.5/5.6
The why and how of moving to PHP 5.5/5.6Wim Godden
23.1K views44 slides
Basicsof c make and git for a hello qt application by
Basicsof c make and git for a hello qt applicationBasicsof c make and git for a hello qt application
Basicsof c make and git for a hello qt applicationDinesh Manajipet
563 views16 slides
Is your code ready for PHP 7 ? by
Is your code ready for PHP 7 ?Is your code ready for PHP 7 ?
Is your code ready for PHP 7 ?Wim Godden
5K views38 slides
Adopt DevOps philosophy on your Symfony projects (Symfony Live 2011) by
Adopt DevOps philosophy on your Symfony projects (Symfony Live 2011)Adopt DevOps philosophy on your Symfony projects (Symfony Live 2011)
Adopt DevOps philosophy on your Symfony projects (Symfony Live 2011)Fabrice Bernhard
3.8K views52 slides
Mojolicious lite by
Mojolicious liteMojolicious lite
Mojolicious liteandrefsantos
1.3K views32 slides

Similar to DWX2015 Code Generierung(20)

PHP QA Tools by rjsmelo
PHP QA ToolsPHP QA Tools
PHP QA Tools
rjsmelo2.1K views
The why and how of moving to PHP 5.5/5.6 by Wim Godden
The why and how of moving to PHP 5.5/5.6The why and how of moving to PHP 5.5/5.6
The why and how of moving to PHP 5.5/5.6
Wim Godden23.1K views
Basicsof c make and git for a hello qt application by Dinesh Manajipet
Basicsof c make and git for a hello qt applicationBasicsof c make and git for a hello qt application
Basicsof c make and git for a hello qt application
Dinesh Manajipet563 views
Is your code ready for PHP 7 ? by Wim Godden
Is your code ready for PHP 7 ?Is your code ready for PHP 7 ?
Is your code ready for PHP 7 ?
Wim Godden5K views
Adopt DevOps philosophy on your Symfony projects (Symfony Live 2011) by Fabrice Bernhard
Adopt DevOps philosophy on your Symfony projects (Symfony Live 2011)Adopt DevOps philosophy on your Symfony projects (Symfony Live 2011)
Adopt DevOps philosophy on your Symfony projects (Symfony Live 2011)
Fabrice Bernhard3.8K views
Custom post-framworks by wcto2017
Custom post-framworksCustom post-framworks
Custom post-framworks
wcto2017970 views
Custom post-framworks by Kiera Howe
Custom post-framworksCustom post-framworks
Custom post-framworks
Kiera Howe71 views
Create your very own Development Environment with Vagrant and Packer by frastel
Create your very own Development Environment with Vagrant and PackerCreate your very own Development Environment with Vagrant and Packer
Create your very own Development Environment with Vagrant and Packer
frastel3.6K views
Composer, putting dependencies on the score by Rafael Dohms
Composer, putting dependencies on the scoreComposer, putting dependencies on the score
Composer, putting dependencies on the score
Rafael Dohms10.1K views
DevOps(4) : Ansible(2) - (MOSG) by Soshi Nemoto
DevOps(4) : Ansible(2) - (MOSG)DevOps(4) : Ansible(2) - (MOSG)
DevOps(4) : Ansible(2) - (MOSG)
Soshi Nemoto851 views
Introduction to Codeigniter by Zero Huang
Introduction to Codeigniter Introduction to Codeigniter
Introduction to Codeigniter
Zero Huang1.6K views
Vitta Minicurso Laravel - Hackathon League of Legends by Filipe Forattini
Vitta Minicurso Laravel - Hackathon League of LegendsVitta Minicurso Laravel - Hackathon League of Legends
Vitta Minicurso Laravel - Hackathon League of Legends
Filipe Forattini496 views
Deploying Symfony | symfony.cat by Pablo Godel
Deploying Symfony | symfony.catDeploying Symfony | symfony.cat
Deploying Symfony | symfony.cat
Pablo Godel2.8K views
Symfony2 for Midgard Developers by Henri Bergius
Symfony2 for Midgard DevelopersSymfony2 for Midgard Developers
Symfony2 for Midgard Developers
Henri Bergius2K views

More from Ralf Eggert

ChatGPT: unser täglich' Bot gib uns heute by
ChatGPT: unser täglich' Bot gib uns heuteChatGPT: unser täglich' Bot gib uns heute
ChatGPT: unser täglich' Bot gib uns heuteRalf Eggert
6 views87 slides
Der ultimative PHP Framework Vergleich 2023 Edition by
Der ultimative PHP Framework Vergleich 2023 EditionDer ultimative PHP Framework Vergleich 2023 Edition
Der ultimative PHP Framework Vergleich 2023 EditionRalf Eggert
3 views79 slides
PHP Module als Rundum-Sorglos-Pakete entwickeln by
PHP Module als Rundum-Sorglos-Pakete entwickelnPHP Module als Rundum-Sorglos-Pakete entwickeln
PHP Module als Rundum-Sorglos-Pakete entwickelnRalf Eggert
70 views70 slides
Alexa, what's next? by
Alexa, what's next?Alexa, what's next?
Alexa, what's next?Ralf Eggert
311 views58 slides
Alexa, wohin geht die Reise by
Alexa, wohin geht die ReiseAlexa, wohin geht die Reise
Alexa, wohin geht die ReiseRalf Eggert
265 views26 slides
8. Hamburg Voice Interface Meetup by
8. Hamburg Voice Interface Meetup8. Hamburg Voice Interface Meetup
8. Hamburg Voice Interface MeetupRalf Eggert
199 views16 slides

More from Ralf Eggert(20)

ChatGPT: unser täglich' Bot gib uns heute by Ralf Eggert
ChatGPT: unser täglich' Bot gib uns heuteChatGPT: unser täglich' Bot gib uns heute
ChatGPT: unser täglich' Bot gib uns heute
Ralf Eggert6 views
Der ultimative PHP Framework Vergleich 2023 Edition by Ralf Eggert
Der ultimative PHP Framework Vergleich 2023 EditionDer ultimative PHP Framework Vergleich 2023 Edition
Der ultimative PHP Framework Vergleich 2023 Edition
Ralf Eggert3 views
PHP Module als Rundum-Sorglos-Pakete entwickeln by Ralf Eggert
PHP Module als Rundum-Sorglos-Pakete entwickelnPHP Module als Rundum-Sorglos-Pakete entwickeln
PHP Module als Rundum-Sorglos-Pakete entwickeln
Ralf Eggert70 views
Alexa, what's next? by Ralf Eggert
Alexa, what's next?Alexa, what's next?
Alexa, what's next?
Ralf Eggert311 views
Alexa, wohin geht die Reise by Ralf Eggert
Alexa, wohin geht die ReiseAlexa, wohin geht die Reise
Alexa, wohin geht die Reise
Ralf Eggert265 views
8. Hamburg Voice Interface Meetup by Ralf Eggert
8. Hamburg Voice Interface Meetup8. Hamburg Voice Interface Meetup
8. Hamburg Voice Interface Meetup
Ralf Eggert199 views
Alexa Skill Maintenance by Ralf Eggert
Alexa Skill MaintenanceAlexa Skill Maintenance
Alexa Skill Maintenance
Ralf Eggert385 views
Vom Zend Framework zu Laminas by Ralf Eggert
Vom Zend Framework zu LaminasVom Zend Framework zu Laminas
Vom Zend Framework zu Laminas
Ralf Eggert441 views
Alexa Skills und PHP? Passt das zusammen? by Ralf Eggert
Alexa Skills und PHP? Passt das zusammen?Alexa Skills und PHP? Passt das zusammen?
Alexa Skills und PHP? Passt das zusammen?
Ralf Eggert426 views
Mit Jovo von 0 auf 100 by Ralf Eggert
Mit Jovo von 0 auf 100Mit Jovo von 0 auf 100
Mit Jovo von 0 auf 100
Ralf Eggert477 views
Vom Zend Framework zu Laminas by Ralf Eggert
Vom Zend Framework zu LaminasVom Zend Framework zu Laminas
Vom Zend Framework zu Laminas
Ralf Eggert490 views
Alexa for Hospitality by Ralf Eggert
Alexa for HospitalityAlexa for Hospitality
Alexa for Hospitality
Ralf Eggert249 views
Alexa, lass uns Geld verdienen – fünf Geschäftsmodelle, die wirklich funktion... by Ralf Eggert
Alexa, lass uns Geld verdienen – fünf Geschäftsmodelle, die wirklich funktion...Alexa, lass uns Geld verdienen – fünf Geschäftsmodelle, die wirklich funktion...
Alexa, lass uns Geld verdienen – fünf Geschäftsmodelle, die wirklich funktion...
Ralf Eggert802 views
Fortgeschrittene Techniken für erfolgreiche Sprachanwendungen by Ralf Eggert
Fortgeschrittene Techniken für erfolgreiche SprachanwendungenFortgeschrittene Techniken für erfolgreiche Sprachanwendungen
Fortgeschrittene Techniken für erfolgreiche Sprachanwendungen
Ralf Eggert336 views
Die sieben Projektphasen für Voice Projekte by Ralf Eggert
Die sieben Projektphasen für Voice ProjekteDie sieben Projektphasen für Voice Projekte
Die sieben Projektphasen für Voice Projekte
Ralf Eggert332 views
Künstliche Intelligenz – Traum und Wirklichkeit by Ralf Eggert
Künstliche Intelligenz – Traum und WirklichkeitKünstliche Intelligenz – Traum und Wirklichkeit
Künstliche Intelligenz – Traum und Wirklichkeit
Ralf Eggert518 views
Multi-Modal Voice Development with Amazon Alexa by Ralf Eggert
Multi-Modal Voice Development with Amazon AlexaMulti-Modal Voice Development with Amazon Alexa
Multi-Modal Voice Development with Amazon Alexa
Ralf Eggert987 views
Mein Haus, mein Auto, mein Backend by Ralf Eggert
Mein Haus, mein Auto, mein BackendMein Haus, mein Auto, mein Backend
Mein Haus, mein Auto, mein Backend
Ralf Eggert171 views
Zend/Expressive 3 – The Next Generation by Ralf Eggert
Zend/Expressive 3 – The Next GenerationZend/Expressive 3 – The Next Generation
Zend/Expressive 3 – The Next Generation
Ralf Eggert364 views

Recently uploaded

The Dark Web : Hidden Services by
The Dark Web : Hidden ServicesThe Dark Web : Hidden Services
The Dark Web : Hidden ServicesAnshu Singh
5 views24 slides
How to think like a threat actor for Kubernetes.pptx by
How to think like a threat actor for Kubernetes.pptxHow to think like a threat actor for Kubernetes.pptx
How to think like a threat actor for Kubernetes.pptxLibbySchulze1
5 views33 slides
hamro digital logics.pptx by
hamro digital logics.pptxhamro digital logics.pptx
hamro digital logics.pptxtupeshghimire
9 views36 slides
WEB 2.O TOOLS: Empowering education.pptx by
WEB 2.O TOOLS: Empowering education.pptxWEB 2.O TOOLS: Empowering education.pptx
WEB 2.O TOOLS: Empowering education.pptxnarmadhamanohar21
16 views16 slides
information by
informationinformation
informationkhelgishekhar
10 views4 slides
Affiliate Marketing by
Affiliate MarketingAffiliate Marketing
Affiliate MarketingNavin Dhanuka
17 views30 slides

Recently uploaded(10)

The Dark Web : Hidden Services by Anshu Singh
The Dark Web : Hidden ServicesThe Dark Web : Hidden Services
The Dark Web : Hidden Services
Anshu Singh5 views
How to think like a threat actor for Kubernetes.pptx by LibbySchulze1
How to think like a threat actor for Kubernetes.pptxHow to think like a threat actor for Kubernetes.pptx
How to think like a threat actor for Kubernetes.pptx
LibbySchulze15 views
PORTFOLIO 1 (Bret Michael Pepito).pdf by brejess0410
PORTFOLIO 1 (Bret Michael Pepito).pdfPORTFOLIO 1 (Bret Michael Pepito).pdf
PORTFOLIO 1 (Bret Michael Pepito).pdf
brejess04109 views
IETF 118: Starlink Protocol Performance by APNIC
IETF 118: Starlink Protocol PerformanceIETF 118: Starlink Protocol Performance
IETF 118: Starlink Protocol Performance
APNIC394 views
Building trust in our information ecosystem: who do we trust in an emergency by Tina Purnat
Building trust in our information ecosystem: who do we trust in an emergencyBuilding trust in our information ecosystem: who do we trust in an emergency
Building trust in our information ecosystem: who do we trust in an emergency
Tina Purnat109 views
Marketing and Community Building in Web3 by Federico Ast
Marketing and Community Building in Web3Marketing and Community Building in Web3
Marketing and Community Building in Web3
Federico Ast14 views

DWX2015 Code Generierung

  • 1. Code-GenerierungCode-Generierung Mit der Konsole  Repository: https://github.com/RalfEggert/dwx2015-code-generierung Slides: http://de.slideshare.net/eggertralf/dwx2015-codegenerierung 1 / 59
  • 2. Über michÜber mich 2 / 59www.RalfEggert.dewww.RalfEggert.de
  • 4. Frage ans PublikumFrage ans Publikum 4 / 59 [b02][b02]
  • 5. Einsatzzwecke: KonsoleEinsatzzwecke: Konsole 5 / 59 Codegenerierung DeploymentSkripte InstallationsSkripte Datenbank Migration SocketServerCron Jobs Spider / Crawler
  • 7. Tools Konsole & CodeTools Konsole & Code 7 / 59 Konsole Code
  • 8. Tools Konsole & CodeTools Konsole & Code 8 / 59 Konsole Code
  • 9. VariantenVarianten 9 / 59 Zend Framework 2 Full-Stack ZF2 Applikation Mit MVC Gute ZF2-Kenntnisse ZendCodeGenerator ZendConsole ZFConsole »Richtige« Konsolen-Anwendung Ohne MVC Wenige ZF2-Kenntnisse ZendCodeGenerator ZendConsole
  • 10. VariantenVarianten 10 / 59 Zend Framework 2 Full-Stack ZF2 Applikation Mit MVC Gute ZF2-Kenntnisse ZendCodeGenerator ZendConsole ZFConsole »Richtige« Konsolen-Anwendung Ohne MVC Wenige ZF2-Kenntnisse ZendCodeGenerator ZendConsole
  • 11. ??? BausteineBausteine 11 / 59 PHP 5.5 C0mposer ZFConsole ZendConsole ZendCode ZendConfig ZendDb ZendFilter ZendValidator
  • 12. Composer.jsonComposer.json 12 / 59 { "name": "ralfeggert/dwx2015-code-generierung", "description": "DWX2015: Tool zur Code-Generierung", "license": "MIT", "require": { "php": ">=5.5", "zfcampus/zf-console": "~1.0", "zendframework/zend-code": "~2.5", "zendframework/zend-config": "~2.5", "zendframework/zend-console": "~2.5", "zendframework/zend-db": "~2.5", "zendframework/zend-filter": "~2.5", "zendframework/zend-validator": "~2.5" }, "autoload": { "psr-4": { "PHPCG": "src/PHPCG" } }, "bin": ["bin/phpcg.php"] }
  • 13. InstallationInstallation 13 / 59 // Projekt klonen $ cd /home/devhost/ $ git clone https://github.com/RalfEggert/dwx2015-code-generierung $ cd dwx2015-code-generierung/ // Abhängigkeiten per Composer installieren $ php composer.phar install // PHP Code Generator ausführen $ bin/phpcg.php
  • 16. ApplicationApplication 16 / 59 <?php // Datei /bin/phpcg.php use ZendConsoleConsole; use ZFConsoleApplication; define('DWX2015_PHPCG_ROOT', __DIR__ . '/..'); define('VERSION', '1.0.0'); include DWX2015_PHPCG_ROOT . '/vendor/autoload.php'; $routes = include DWX2015_PHPCG_ROOT . '/config/routes.php'; $console = Console::getInstance(); $application = new Application( 'PHP Code Generator (DWX2015)', VERSION, $routes, $console ); $exit = $application->run(); exit($exit);
  • 17. AutovervollständigungAutovervollständigung 17 / 59 // Autovervollständigung einrichten $ sudo bin/phpcg.php autocomplete > /etc/bash_completion.d/phpcg.php.sh $ source /etc/bash_completion.d/phpcg.php.sh // Autovervollständigung nutzen $ bin/phpcg.php <TAB> autocomplete create-hello-you-class create-user-entities hello-someone hello-world hello-you update-user-entities help version
  • 18. PHAR GenerierenPHAR Generieren 18 / 59 // PHAR Paket erstellen lassen $ bin/create-phar.php Phar created successfully in /home/devhost/dwx2015-code-generate/phpcg.phar // Phar Paket verwenden $ php phpcg.phar --------------------------------------------------------------------------- PHP Code Generator (DWX2015), version 1.0.0 Available commands: autocomplete Command autocompletion setup create-hello-you-class Create hello you class create-user-entities Create user entities hello-someone Hello someone hello-world Hello world hello-you Hello you help Get help for individual commands update-user-entities Update user entities version Display the version of the script ---------------------------------------------------------------------------
  • 19. HilfeHilfe 19 / 59 // Autovervollständigung einrichten $ bin/phpcg.php help --------------------------------------------------------------------------- PHP Code Generator (DWX2015), version 1.0.0 Available commands: autocomplete Command autocompletion setup create-hello-you-class Create hello you class create-user-entities Create user entities hello-someone Hello someone hello-world Hello world hello-you Hello you help Get help for individual commands update-user-entities Update user entities version Display the version of the script ---------------------------------------------------------------------------
  • 20. Routing BeispieleRouting Beispiele 20 / 59 // Route ohne Parameter 'say-stuff' $ bin/phpcg.php say-stuff // Route mit obligatorischem Wertparameter 'say-stuff <stuff>' $ bin/phpcg.php say-stuff Whatever // Route mit optionalem Flag 'do-stuff [--strict|-s]:strict' $ bin/phpcg.php do-stuff -s // Route mit optionalem Wertparameter 'do-stuff [--target=]' $ bin/phpcg.php do-stuff --target=Whatever
  • 22. RouteRoute 22 / 59 <?php // Datei /config/routes.php return array( array( 'name' => 'hello-world', 'route' => 'hello-world', 'description' => 'Say hello to the world', 'short_description' => 'Hello world', 'handler' => 'PHPCGCommandHelloWorld', ), [...] );
  • 23. KommandoKommando 23 / 59 <?php // Datei /src/PHPCG/Command/HelloWorld.php namespace PHPCGCommand; use ZendConsoleAdapterAdapterInterface as Console; use ZendConsoleColorInterface as Color; use ZFConsoleRoute; class HelloWorld { public function __invoke(Route $route, Console $console) { $console->writeLine('Hello World', Color::YELLOW); } }
  • 24. KonsoleKonsole 24 / 59 $ bin/phpcg.php hello-world --------------------------------------------------------------------------- PHP Code Generator (DWX2015), version 1.0.0 Hello World ---------------------------------------------------------------------------
  • 25. RouteRoute 25 / 59 <?php // Datei /config/routes.php return array( array( 'name' => 'hello-you', 'route' => 'hello-you <you>', 'description' => 'Say hello to you', 'short_description' => 'Hello you', 'options_descriptions' => array( '<you>' => 'Your name' ), 'handler' => 'PHPCGCommandHelloYou', ), [...] );
  • 26. KommandoKommando 26 / 59 <?php // Datei /src/PHPCG/Command/HelloYou.php namespace PHPCGCommand; use ZendConsoleAdapterAdapterInterface as Console; use ZendConsoleColorInterface as Color; use ZFConsoleRoute; class HelloYou { public function __invoke(Route $route, Console $console) { $you = $route->getMatchedParam('you'); $console->write('Hello '); $console->write(sprintf('"%s"', $you), Color::YELLOW); $console->writeLine(' ...'); } }
  • 27. KonsoleKonsole 27 / 59 $ bin/phpcg.php hello-you Ralf --------------------------------------------------------------------------- PHP Code Generator (DWX2015), version 1.0.0 Hello "Ralf" ... ---------------------------------------------------------------------------
  • 28. RouteRoute 28 / 59 <?php // Datei /config/routes.php return array( array( 'name' => 'hello-someone', 'route' => 'hello-someone', 'description' => 'Say hello to someone', 'short_description' => 'Hello someone', 'handler' => 'PHPCGCommandHelloSomeOne', ), [...] );
  • 29. KommandoKommando 29 / 59 <?php // Datei /src/PHPCG/Command/HelloSomeOne.php [...] use ZendConsolePromptLine; use ZendConsolePromptSelect; class HelloSomeOne { public function __invoke(Route $route, Console $console) { $prompt = new Line('Please enter any name: '); $you = $prompt->show(); $options = array(Color::BLACK => 'BLACK', [...], Color::BLUE => 'BLUE'); $prompt = new Select('Please choose any color: ', $options); $color = $prompt->show(); $console->write('Hello '); $console->write(sprintf(' %s ', $you), Color::WHITE, $color); $console->writeLine(' ...'); } }
  • 30. KonsoleKonsole 30 / 59 $ bin/phpcg.php hello-someone --------------------------------------------------------------------------- PHP Code Generator (DWX2015), version 1.0.0 Please enter any name: Ralf Please choose any color: 1) BLACK 2) RED 3) GREEN 4) YELLOW 5) BLUE Hello ... --------------------------------------------------------------------------- ralf@ralf-HP-2013:/home/devhost/dwx2015-code-generierung$ Ralf
  • 33. GeneratorenGeneratoren 33 / 59 Body Generator Class Generator Doc Block Generator FileGenerator Method Generator Parameter Generator PropertyGenerator TRAIT Generator Value Generator Weitere Generatoren
  • 34. RouteRoute 34 / 59 <?php // Datei /config/routes.php return array( array( 'name' => 'create-hello-you-class', 'route' => 'create-hello-you-class', 'description' => 'Create a hello you class', 'short_description' => 'Create hello you class', 'handler' => 'PHPCGCommandCreateHelloYou', ), [...] );
  • 35. Class Generator IClass Generator I 35 / 59 <?php // Datei /src/PHPCG/Generator/HelloYouClassGenerator.php namespace PHPCGGenerator; use ZendCodeGeneratorClassGenerator; use ZendCodeGeneratorMethodGenerator; use ZendCodeGeneratorParameterGenerator; use ZendCodeGeneratorPropertyGenerator; class HelloYouClassGenerator { private $class; public function getClass() { return $this->class; } public function createClass() {} }
  • 36. Class Generator IIClass Generator II 36 / 59 <?php public function createClass() { $nameProperty = new PropertyGenerator('name'); $nameProperty->addFlag(PropertyGenerator::FLAG_PRIVATE); $nameSetMethod = new MethodGenerator('setName'); $nameSetMethod->addFlag(MethodGenerator::FLAG_PUBLIC); $nameSetMethod->setParameter(new ParameterGenerator('name')); $nameSetMethod->setBody('$this->name = $name;'); $greetMethod = new MethodGenerator('greet'); $greetMethod->addFlag(MethodGenerator::FLAG_PUBLIC); $greetMethod->setBody('return sprintf("Hello %s!", $this->name);'); $this->class = new ClassGenerator('HelloYou', 'HelloGreeting'); $this->class->addPropertyFromGenerator($nameProperty); $this->class->addMethods(array($nameSetMethod, $greetMethod)); }
  • 37. FILE GeneratorFILE Generator 37 / 59 <?php // Datei /src/PHPCG/Generator/ClassFileGenerator.php namespace PHPCGGenerator; use ZendCodeGeneratorClassGenerator; use ZendCodeGeneratorDocBlockGenerator; use ZendCodeGeneratorFileGenerator; class ClassFileGenerator { private $file; public function getFile() { return $this->file; } public function createFile(ClassGenerator $class) { $docBlock = new DocBlockGenerator([...]); $this->file = new FileGenerator(); $this->file->setClass($class); $this->file->setDocBlock($docBlock); } }
  • 38. KommandoKommando 38 / 59 <?php // Datei /src/PHPCG/Command/CreateHelloYouClass.php namespace PHPCGCommand; [...] class CreateHelloYouClass { public function __invoke(Route $route, Console $console) { $fileName = DWX2015_PHPCG_ROOT . '/tmp/HelloYouClass.php'; $classGenerator = new HelloYouClassGenerator(); $classGenerator->createClass(); $class = $classGenerator->getClass(); $fileGenerator = new ClassFileGenerator(); $fileGenerator->createFile($class); $file = $fileGenerator->getFile(); file_put_contents($fileName, $file->generate()); [...] } }
  • 39. KonsoleKonsole 39 / 59 $ bin/phpcg.php create-hello-you-class ---------------------------------------------------------------------------------------- PHP Code Generator (DWX2015), version 1.0.0 Created class HelloYou in file /home/devhost/dwx2015-code-generierung/tmp/HelloYouClass.php <?php namespace HelloGreeting; class HelloYou { private $name = null; public function setName($name) { $this->name = $name; } public function greet() { return sprintf("Hello %s!", $this->name); } } ----------------------------------------------------------------------------------------
  • 42. ZendDb KomponentenZendDb Komponenten 42 / 59 Adapter Metadata Result Set RowGateway SQL Table Gateway
  • 44. DB KonfigurationDB Konfiguration 44 / 59 <?php // Datei /config/db.php return array( 'adapter' => array( 'driver' => 'Pdo', 'dsn' => 'mysql:dbname=dwx2015.user;host=localhost;charset=utf8', 'user' => 'dwx2015', 'pass' => 'dwx2015', ), );
  • 45. Meta Data Collector IMeta Data Collector I 45 / 59 <?php // Datei /src/PHPCG/MetaData/Collector.php namespace PHPCGCollector; use ZendDbMetadataMetadata; use ZendDbMetadataObjectColumnObject; class MetaDataCollector { public function __construct(Metadata $metaData) { $this->metaData = $metaData; } public function fetchTableColumns($tableName) { $tableColumns = array(); [...] return $tableColumns; } }
  • 46. Meta Data Collector IIMeta Data Collector II 46 / 59 <?php [...] foreach ($tableMeta->getColumns() as $column) { $config = array('required' => !$column->getIsNullable()); if (in_array($column->getDataType(), array('varchar','text','enum'))) { $config['type'] = 'string'; } else { $config['type'] = 'integer'; } if ($column->getDataType() == 'varchar') { $config['max_length'] = $column->getCharacterMaximumLength(); } elseif ($column->getDataType() == 'enum') { $config['values'] = $column->getErrata('permitted_values'); } $tableColumns[$column->getName()] = $config; }
  • 47. User Entity Generator IUser Entity Generator I 47 / 59 <?php // Datei /src/PHPCG/Generator/UserEntityGenerator.php namespace PHPCGGenerator; use ZendCodeGeneratorClassGenerator; use ZendCodeGeneratorDocBlockGenerator; use ZendCodeGeneratorMethodGenerator; use ZendCodeGeneratorParameterGenerator; use ZendCodeGeneratorPropertyGenerator; use ZendCodeGeneratorValueGenerator; use ZendFilterWordUnderscoreToCamelCase; class UserEntityGenerator extends ClassGenerator { private $class; private $filterUTCC; public function __construct() {} public function getClass() {} public function createClass() {} public function addEntityProperties(array $columns = array()) {} }
  • 48. User Entity Generator IIUser Entity Generator II 48 / 59 <?php public function __construct() { $this->filterUTCC = new UnderscoreToCamelCase(); } public function getClass() { return $this->class; } public function createClass() { $this->class = new ClassGenerator('UserEntity', 'UserEntity'); $this->class->setDocBlock( new DocBlockGenerator([...]) ); }
  • 49. User Entity Generator IIIUser Entity Generator III 49 / 59 <?php public function addEntityProperties() { foreach ($this->columns as $name => $attributes) { $property = $this->generateProperty($name, $attributes); $getMethod = $this->generateGetMethod($name, $attributes); $setMethod = $this->generateSetMethod($name, $attributes); $this->class->addPropertyFromGenerator($property); $this->class->addMethodFromGenerator($getMethod); $this->class->addMethodFromGenerator($setMethod); } } private function generateProperty($name, array $attributes = array()) { $property = new PropertyGenerator($name); $property->addFlag(PropertyGenerator::FLAG_PROTECTED); return $property; }
  • 50. User Entity Generator IVUser Entity Generator IV 50 / 59 <?php private function generateGetMethod($name, array $attributes = array()) { $methodName = 'get' . $this->filterUTCC->filter($name); $getMethod = new MethodGenerator($methodName); $getMethod->addFlag(MethodGenerator::FLAG_PUBLIC); $getMethod->setBody('return $this->' . $name . ';'); return $getMethod; }
  • 51. User Entity Generator VUser Entity Generator V 51 / 59 <?php private function generateSetMethod($name, array $attribs = array()) { $methodName = 'set' . $this->filterUTCC->filter($name); $defaultValue = !$attribs['required'] ? new ValueGenerator(null) : null; $setMethod = new MethodGenerator($methodName); $setMethod->addFlag(MethodGenerator::FLAG_PUBLIC); $setMethod->setParameter( new ParameterGenerator($name, null, $defaultValue) ); $setMethod->setBody('$this->' . $name . ' = $' . $name . ';'); return $setMethod; }
  • 52. Kommando IKommando I 52 / 59 <?php // Datei /src/PHPCG/Command/CreateUserEntities.php namespace PHPCGCommand; use PHPCGCollectorMetaDataCollector; use PHPCGGeneratorClassFileGenerator; use PHPCGGeneratorUserEntityGenerator; use ZendConsoleAdapterAdapterInterface as Console; use ZendConsoleColorInterface as Color; use ZendDbAdapterAdapter; use ZendDbMetadataMetadata; use ZFConsoleRoute; class CreateUserEntities { public function __invoke(Route $route, Console $console) { [...] } }
  • 53. Kommando IIKommando II 53 / 59 <?php public function __invoke(Route $route, Console $console) { $dbConfig = include DWX2015_PHPCG_ROOT . '/config/db.php'; $fileName = DWX2015_PHPCG_ROOT . '/tmp/UserEntity.php'; $dbAdapter = new Adapter($dbConfig['adapter']); $metaData = new Metadata($dbAdapter); $collector = new MetaDataCollector($metaData); $userColumns = $collector->fetchTableColumns('user'); $classGenerator = new UserEntityGenerator(); $classGenerator->createClass(); $classGenerator->addEntityProperties($userColumns); $class = $classGenerator->getClass(); $fileGenerator = new ClassFileGenerator(); $fileGenerator->createFile($class); $file = $fileGenerator->getFile(); file_put_contents($fileName, $file->generate()); [...] }
  • 54. KonsoleKonsole 54 / 59 $ bin/phpcg.php create-user-entities ------------------------------------------------------------------------------------------------- PHP Code Generator (DWX2015), version 1.0.0 Created class UserEntity in file /home/devhost/dwx2015-code-generierung/tmp/UserEntity.php <?php namespace UserEntity; class UserEntity { protected $id = null; [...] public function getId() { return $this->id; } public function setId($id) { $this->id = $id; } [...] } -------------------------------------------------------------------------------------------------
  • 55. [B07] War es das?War es das? 55 / 59
  • 56. Weitere IdeenWeitere Ideen 56 / 59 Entities Aktualisieren ✓ Formulare generieren Validierung In Entity ✓ Entities löschen InputFilter Generieren
  • 57. Fragen vom Publikum?Fragen vom Publikum? 57 / 59 [b08]
  • 58. DANKEDANKE Für Ihre / Eure Aufmerksamkeit!  Repository: https://github.com/RalfEggert/dwx2015-code-generierung Slides: http://de.slideshare.net/eggertralf/dwx2015-codegenerierung 58 / 59
  • 59. BildnachweisBildnachweis [B00] Fotos von Ralf Eggert [B01] Carrot And Stick Incentives Lead Manage http://www.workcompass.com/ von Alan O'Rourke - CC-BY https://creativecommons.org/licenses/by/2.0/ [B02] Frontiers 2011 - Day 2 https://www.flickr.com/photos/frontiersofinteraction/5866676276/ von Frontiersofinteraction - CC-BY https://creativecommons.org/licenses/by/2.0/ [B03] Multi Tools https://www.flickr.com/photos/pennuja/5363515039 von Jim Pennucci - CC-BY https://creativecommons.org/licenses/by/2.0/ [B04] Command https://www.flickr.com/photos/shearforce/3838603833/ von Margaret Shear - CC-BY-SA https://creativecommons.org/licenses/by-sa/2.0/ [B05] Propeller Generator in the Sunset https://www.flickr.com/photos/jiazi/2060352110/ von Tim Wang - CC-BY-SA https://creativecommons.org/licenses/by-sa/2.0/ [B06] Fixing the database https://www.flickr.com/photos/dahlstroms/4140461901 von Håkan Dahlström - CC-BY https://creativecommons.org/licenses/by/2.0/ [B07] I have an idea @ home https://www.flickr.com/photos/ful1to/3783198574/ von Julian Santacruz - CC-BY https://creativecommons.org/licenses/by/2.0/ [B08] Etech05: Audience https://www.flickr.com/photos/oreilly/6648470 von James Duncan Davidson - CC-BY https://creativecommons.org/licenses/by/2.0/ Alle weiteren Screenshots wurden von Ralf Eggert erstellt. 59 / 59