SlideShare une entreprise Scribd logo
1  sur  59
Télécharger pour lire hors ligne
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

Contenu connexe

Similaire à DWX2015 Code Generierung

Similaire à DWX2015 Code Generierung (20)

PHP QA Tools
PHP QA ToolsPHP QA Tools
PHP QA Tools
 
The why and how of moving to PHP 5.5/5.6
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
 
Basicsof c make and git for a hello qt application
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
 
Is your code ready for PHP 7 ?
Is your code ready for PHP 7 ?Is your code ready for PHP 7 ?
Is your code ready for PHP 7 ?
 
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)
Adopt DevOps philosophy on your Symfony projects (Symfony Live 2011)
 
Mojolicious lite
Mojolicious liteMojolicious lite
Mojolicious lite
 
LFI to RCE Exploit with Perl Script
LFI to RCE Exploit with Perl ScriptLFI to RCE Exploit with Perl Script
LFI to RCE Exploit with Perl Script
 
Custom post-framworks
Custom post-framworksCustom post-framworks
Custom post-framworks
 
Custom post-framworks
Custom post-framworksCustom post-framworks
Custom post-framworks
 
Create your very own Development Environment with Vagrant and Packer
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
 
Basic Linux kernel
Basic Linux kernelBasic Linux kernel
Basic Linux kernel
 
Composer, putting dependencies on the score
Composer, putting dependencies on the scoreComposer, putting dependencies on the score
Composer, putting dependencies on the score
 
FreeBSD: Dev to Prod
FreeBSD: Dev to ProdFreeBSD: Dev to Prod
FreeBSD: Dev to Prod
 
DevOps(4) : Ansible(2) - (MOSG)
DevOps(4) : Ansible(2) - (MOSG)DevOps(4) : Ansible(2) - (MOSG)
DevOps(4) : Ansible(2) - (MOSG)
 
R-House (LSRC)
R-House (LSRC)R-House (LSRC)
R-House (LSRC)
 
Introduction to Codeigniter
Introduction to Codeigniter Introduction to Codeigniter
Introduction to Codeigniter
 
Vitta Minicurso Laravel - Hackathon League of Legends
Vitta Minicurso Laravel - Hackathon League of LegendsVitta Minicurso Laravel - Hackathon League of Legends
Vitta Minicurso Laravel - Hackathon League of Legends
 
Build Automation 101
Build Automation 101Build Automation 101
Build Automation 101
 
Deploying Symfony | symfony.cat
Deploying Symfony | symfony.catDeploying Symfony | symfony.cat
Deploying Symfony | symfony.cat
 
Symfony2 for Midgard Developers
Symfony2 for Midgard DevelopersSymfony2 for Midgard Developers
Symfony2 for Midgard Developers
 

Plus de Ralf Eggert

Plus de Ralf Eggert (20)

ChatGPT: unser täglich' Bot gib uns heute
ChatGPT: unser täglich' Bot gib uns heuteChatGPT: unser täglich' Bot gib uns heute
ChatGPT: unser täglich' Bot gib uns heute
 
Der ultimative PHP Framework Vergleich 2023 Edition
Der ultimative PHP Framework Vergleich 2023 EditionDer ultimative PHP Framework Vergleich 2023 Edition
Der ultimative PHP Framework Vergleich 2023 Edition
 
PHP Module als Rundum-Sorglos-Pakete entwickeln
PHP Module als Rundum-Sorglos-Pakete entwickelnPHP Module als Rundum-Sorglos-Pakete entwickeln
PHP Module als Rundum-Sorglos-Pakete entwickeln
 
Alexa, what's next?
Alexa, what's next?Alexa, what's next?
Alexa, what's next?
 
Alexa, wohin geht die Reise
Alexa, wohin geht die ReiseAlexa, wohin geht die Reise
Alexa, wohin geht die Reise
 
8. Hamburg Voice Interface Meetup
8. Hamburg Voice Interface Meetup8. Hamburg Voice Interface Meetup
8. Hamburg Voice Interface Meetup
 
Welcome Bixby
Welcome BixbyWelcome Bixby
Welcome Bixby
 
Alexa Skill Maintenance
Alexa Skill MaintenanceAlexa Skill Maintenance
Alexa Skill Maintenance
 
Vom Zend Framework zu Laminas
Vom Zend Framework zu LaminasVom Zend Framework zu Laminas
Vom Zend Framework zu Laminas
 
Alexa Skills und PHP? Passt das zusammen?
Alexa Skills und PHP? Passt das zusammen?Alexa Skills und PHP? Passt das zusammen?
Alexa Skills und PHP? Passt das zusammen?
 
Mit Jovo von 0 auf 100
Mit Jovo von 0 auf 100Mit Jovo von 0 auf 100
Mit Jovo von 0 auf 100
 
Vom Zend Framework zu Laminas
Vom Zend Framework zu LaminasVom Zend Framework zu Laminas
Vom Zend Framework zu Laminas
 
Alexa for Hospitality
Alexa for HospitalityAlexa for Hospitality
Alexa for Hospitality
 
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...
Alexa, lass uns Geld verdienen – fünf Geschäftsmodelle, die wirklich funktion...
 
Fortgeschrittene Techniken für erfolgreiche Sprachanwendungen
Fortgeschrittene Techniken für erfolgreiche SprachanwendungenFortgeschrittene Techniken für erfolgreiche Sprachanwendungen
Fortgeschrittene Techniken für erfolgreiche Sprachanwendungen
 
Die sieben Projektphasen für Voice Projekte
Die sieben Projektphasen für Voice ProjekteDie sieben Projektphasen für Voice Projekte
Die sieben Projektphasen für Voice Projekte
 
Künstliche Intelligenz – Traum und Wirklichkeit
Künstliche Intelligenz – Traum und WirklichkeitKünstliche Intelligenz – Traum und Wirklichkeit
Künstliche Intelligenz – Traum und Wirklichkeit
 
Multi-Modal Voice Development with Amazon Alexa
Multi-Modal Voice Development with Amazon AlexaMulti-Modal Voice Development with Amazon Alexa
Multi-Modal Voice Development with Amazon Alexa
 
Mein Haus, mein Auto, mein Backend
Mein Haus, mein Auto, mein BackendMein Haus, mein Auto, mein Backend
Mein Haus, mein Auto, mein Backend
 
Zend/Expressive 3 – The Next Generation
Zend/Expressive 3 – The Next GenerationZend/Expressive 3 – The Next Generation
Zend/Expressive 3 – The Next Generation
 

Dernier

pdfcoffee.com_business-ethics-q3m7-pdf-free.pdf
pdfcoffee.com_business-ethics-q3m7-pdf-free.pdfpdfcoffee.com_business-ethics-q3m7-pdf-free.pdf
pdfcoffee.com_business-ethics-q3m7-pdf-free.pdf
JOHNBEBONYAP1
 
PowerDirector Explination Process...pptx
PowerDirector Explination Process...pptxPowerDirector Explination Process...pptx
PowerDirector Explination Process...pptx
galaxypingy
 
Russian Call girls in Abu Dhabi 0508644382 Abu Dhabi Call girls
Russian Call girls in Abu Dhabi 0508644382 Abu Dhabi Call girlsRussian Call girls in Abu Dhabi 0508644382 Abu Dhabi Call girls
Russian Call girls in Abu Dhabi 0508644382 Abu Dhabi Call girls
Monica Sydney
 
一比一原版(Offer)康考迪亚大学毕业证学位证靠谱定制
一比一原版(Offer)康考迪亚大学毕业证学位证靠谱定制一比一原版(Offer)康考迪亚大学毕业证学位证靠谱定制
一比一原版(Offer)康考迪亚大学毕业证学位证靠谱定制
pxcywzqs
 
一比一原版(Curtin毕业证书)科廷大学毕业证原件一模一样
一比一原版(Curtin毕业证书)科廷大学毕业证原件一模一样一比一原版(Curtin毕业证书)科廷大学毕业证原件一模一样
一比一原版(Curtin毕业证书)科廷大学毕业证原件一模一样
ayvbos
 
原版制作美国爱荷华大学毕业证(iowa毕业证书)学位证网上存档可查
原版制作美国爱荷华大学毕业证(iowa毕业证书)学位证网上存档可查原版制作美国爱荷华大学毕业证(iowa毕业证书)学位证网上存档可查
原版制作美国爱荷华大学毕业证(iowa毕业证书)学位证网上存档可查
ydyuyu
 
Indian Escort in Abu DHabi 0508644382 Abu Dhabi Escorts
Indian Escort in Abu DHabi 0508644382 Abu Dhabi EscortsIndian Escort in Abu DHabi 0508644382 Abu Dhabi Escorts
Indian Escort in Abu DHabi 0508644382 Abu Dhabi Escorts
Monica Sydney
 
哪里办理美国迈阿密大学毕业证(本硕)umiami在读证明存档可查
哪里办理美国迈阿密大学毕业证(本硕)umiami在读证明存档可查哪里办理美国迈阿密大学毕业证(本硕)umiami在读证明存档可查
哪里办理美国迈阿密大学毕业证(本硕)umiami在读证明存档可查
ydyuyu
 
Top profile Call Girls In Dindigul [ 7014168258 ] Call Me For Genuine Models ...
Top profile Call Girls In Dindigul [ 7014168258 ] Call Me For Genuine Models ...Top profile Call Girls In Dindigul [ 7014168258 ] Call Me For Genuine Models ...
Top profile Call Girls In Dindigul [ 7014168258 ] Call Me For Genuine Models ...
gajnagarg
 

Dernier (20)

pdfcoffee.com_business-ethics-q3m7-pdf-free.pdf
pdfcoffee.com_business-ethics-q3m7-pdf-free.pdfpdfcoffee.com_business-ethics-q3m7-pdf-free.pdf
pdfcoffee.com_business-ethics-q3m7-pdf-free.pdf
 
20240509 QFM015 Engineering Leadership Reading List April 2024.pdf
20240509 QFM015 Engineering Leadership Reading List April 2024.pdf20240509 QFM015 Engineering Leadership Reading List April 2024.pdf
20240509 QFM015 Engineering Leadership Reading List April 2024.pdf
 
APNIC Updates presented by Paul Wilson at ARIN 53
APNIC Updates presented by Paul Wilson at ARIN 53APNIC Updates presented by Paul Wilson at ARIN 53
APNIC Updates presented by Paul Wilson at ARIN 53
 
Power point inglese - educazione civica di Nuria Iuzzolino
Power point inglese - educazione civica di Nuria IuzzolinoPower point inglese - educazione civica di Nuria Iuzzolino
Power point inglese - educazione civica di Nuria Iuzzolino
 
Nagercoil Escorts Service Girl ^ 9332606886, WhatsApp Anytime Nagercoil
Nagercoil Escorts Service Girl ^ 9332606886, WhatsApp Anytime NagercoilNagercoil Escorts Service Girl ^ 9332606886, WhatsApp Anytime Nagercoil
Nagercoil Escorts Service Girl ^ 9332606886, WhatsApp Anytime Nagercoil
 
PowerDirector Explination Process...pptx
PowerDirector Explination Process...pptxPowerDirector Explination Process...pptx
PowerDirector Explination Process...pptx
 
Russian Call girls in Abu Dhabi 0508644382 Abu Dhabi Call girls
Russian Call girls in Abu Dhabi 0508644382 Abu Dhabi Call girlsRussian Call girls in Abu Dhabi 0508644382 Abu Dhabi Call girls
Russian Call girls in Abu Dhabi 0508644382 Abu Dhabi Call girls
 
一比一原版(Offer)康考迪亚大学毕业证学位证靠谱定制
一比一原版(Offer)康考迪亚大学毕业证学位证靠谱定制一比一原版(Offer)康考迪亚大学毕业证学位证靠谱定制
一比一原版(Offer)康考迪亚大学毕业证学位证靠谱定制
 
Meaning of On page SEO & its process in detail.
Meaning of On page SEO & its process in detail.Meaning of On page SEO & its process in detail.
Meaning of On page SEO & its process in detail.
 
一比一原版(Curtin毕业证书)科廷大学毕业证原件一模一样
一比一原版(Curtin毕业证书)科廷大学毕业证原件一模一样一比一原版(Curtin毕业证书)科廷大学毕业证原件一模一样
一比一原版(Curtin毕业证书)科廷大学毕业证原件一模一样
 
Trump Diapers Over Dems t shirts Sweatshirt
Trump Diapers Over Dems t shirts SweatshirtTrump Diapers Over Dems t shirts Sweatshirt
Trump Diapers Over Dems t shirts Sweatshirt
 
20240507 QFM013 Machine Intelligence Reading List April 2024.pdf
20240507 QFM013 Machine Intelligence Reading List April 2024.pdf20240507 QFM013 Machine Intelligence Reading List April 2024.pdf
20240507 QFM013 Machine Intelligence Reading List April 2024.pdf
 
"Boost Your Digital Presence: Partner with a Leading SEO Agency"
"Boost Your Digital Presence: Partner with a Leading SEO Agency""Boost Your Digital Presence: Partner with a Leading SEO Agency"
"Boost Your Digital Presence: Partner with a Leading SEO Agency"
 
原版制作美国爱荷华大学毕业证(iowa毕业证书)学位证网上存档可查
原版制作美国爱荷华大学毕业证(iowa毕业证书)学位证网上存档可查原版制作美国爱荷华大学毕业证(iowa毕业证书)学位证网上存档可查
原版制作美国爱荷华大学毕业证(iowa毕业证书)学位证网上存档可查
 
Indian Escort in Abu DHabi 0508644382 Abu Dhabi Escorts
Indian Escort in Abu DHabi 0508644382 Abu Dhabi EscortsIndian Escort in Abu DHabi 0508644382 Abu Dhabi Escorts
Indian Escort in Abu DHabi 0508644382 Abu Dhabi Escorts
 
哪里办理美国迈阿密大学毕业证(本硕)umiami在读证明存档可查
哪里办理美国迈阿密大学毕业证(本硕)umiami在读证明存档可查哪里办理美国迈阿密大学毕业证(本硕)umiami在读证明存档可查
哪里办理美国迈阿密大学毕业证(本硕)umiami在读证明存档可查
 
APNIC Policy Roundup, presented by Sunny Chendi at the 5th ICANN APAC-TWNIC E...
APNIC Policy Roundup, presented by Sunny Chendi at the 5th ICANN APAC-TWNIC E...APNIC Policy Roundup, presented by Sunny Chendi at the 5th ICANN APAC-TWNIC E...
APNIC Policy Roundup, presented by Sunny Chendi at the 5th ICANN APAC-TWNIC E...
 
Real Men Wear Diapers T Shirts sweatshirt
Real Men Wear Diapers T Shirts sweatshirtReal Men Wear Diapers T Shirts sweatshirt
Real Men Wear Diapers T Shirts sweatshirt
 
Story Board.pptxrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr
Story Board.pptxrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrStory Board.pptxrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr
Story Board.pptxrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr
 
Top profile Call Girls In Dindigul [ 7014168258 ] Call Me For Genuine Models ...
Top profile Call Girls In Dindigul [ 7014168258 ] Call Me For Genuine Models ...Top profile Call Girls In Dindigul [ 7014168258 ] Call Me For Genuine Models ...
Top profile Call Girls In Dindigul [ 7014168258 ] Call Me For Genuine Models ...
 

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