SlideShare a Scribd company logo
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

More Related Content

PDF
Zend\Expressive - höher, schneller, weiter
PDF
DevOps in PHP environment
PDF
Composer for busy developers - DPC13
PDF
Designing High Performance RTC Signaling Servers
PDF
Kicking off with Zend Expressive and Doctrine ORM (PHPNW2016)
PDF
Artificial Neural Network in a Tic Tac Toe Symfony Console Application - Symf...
PDF
Aynchronous Processing in Kamailio Configuration File
PDF
php & performance
Zend\Expressive - höher, schneller, weiter
DevOps in PHP environment
Composer for busy developers - DPC13
Designing High Performance RTC Signaling Servers
Kicking off with Zend Expressive and Doctrine ORM (PHPNW2016)
Artificial Neural Network in a Tic Tac Toe Symfony Console Application - Symf...
Aynchronous Processing in Kamailio Configuration File
php & performance

More from Ralf Eggert (20)

PDF
PHP Frameworks: I want to break free (IPC Berlin 2024)
PDF
PHP Rewrite: Do the right thing (IPC Berlin 2024)
PDF
ChatGPT: unser täglich' Bot gib uns heute
PDF
Der ultimative PHP Framework Vergleich 2023 Edition
PDF
PHP Module als Rundum-Sorglos-Pakete entwickeln
PDF
Alexa, what's next?
PDF
Alexa, wohin geht die Reise
PDF
8. Hamburg Voice Interface Meetup
PDF
Welcome Bixby
PDF
Alexa Skill Maintenance
PDF
Vom Zend Framework zu Laminas
PDF
Alexa Skills und PHP? Passt das zusammen?
PDF
Mit Jovo von 0 auf 100
PDF
Vom Zend Framework zu Laminas
PDF
Alexa for Hospitality
PDF
Alexa, lass uns Geld verdienen – fünf Geschäftsmodelle, die wirklich funktion...
PDF
Fortgeschrittene Techniken für erfolgreiche Sprachanwendungen
PDF
Die sieben Projektphasen für Voice Projekte
PDF
Künstliche Intelligenz – Traum und Wirklichkeit
PDF
Multi-Modal Voice Development with Amazon Alexa
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Rewrite: Do the right thing (IPC Berlin 2024)
ChatGPT: unser täglich' Bot gib uns heute
Der ultimative PHP Framework Vergleich 2023 Edition
PHP Module als Rundum-Sorglos-Pakete entwickeln
Alexa, what's next?
Alexa, wohin geht die Reise
8. Hamburg Voice Interface Meetup
Welcome Bixby
Alexa Skill Maintenance
Vom Zend Framework zu Laminas
Alexa Skills und PHP? Passt das zusammen?
Mit Jovo von 0 auf 100
Vom Zend Framework zu Laminas
Alexa for Hospitality
Alexa, lass uns Geld verdienen – fünf Geschäftsmodelle, die wirklich funktion...
Fortgeschrittene Techniken für erfolgreiche Sprachanwendungen
Die sieben Projektphasen für Voice Projekte
Künstliche Intelligenz – Traum und Wirklichkeit
Multi-Modal Voice Development with Amazon Alexa
Ad

Recently uploaded (20)

PDF
Slides PDF The World Game (s) Eco Economic Epochs.pdf
PDF
An introduction to the IFRS (ISSB) Stndards.pdf
PPTX
CHE NAA, , b,mn,mblblblbljb jb jlb ,j , ,C PPT.pptx
PPTX
Digital Literacy And Online Safety on internet
PPTX
INTERNET------BASICS-------UPDATED PPT PRESENTATION
PDF
Introduction to the IoT system, how the IoT system works
PPT
isotopes_sddsadsaadasdasdasdasdsa1213.ppt
PPTX
artificial intelligence overview of it and more
PPTX
June-4-Sermon-Powerpoint.pptx USE THIS FOR YOUR MOTIVATION
PDF
Decoding a Decade: 10 Years of Applied CTI Discipline
PPTX
innovation process that make everything different.pptx
PDF
Tenda Login Guide: Access Your Router in 5 Easy Steps
PPTX
Introduction about ICD -10 and ICD11 on 5.8.25.pptx
DOCX
Unit-3 cyber security network security of internet system
PDF
Cloud-Scale Log Monitoring _ Datadog.pdf
PDF
APNIC Update, presented at PHNOG 2025 by Shane Hermoso
PPTX
E -tech empowerment technologies PowerPoint
PDF
The Internet -By the Numbers, Sri Lanka Edition
PDF
How to Ensure Data Integrity During Shopify Migration_ Best Practices for Sec...
PDF
WebRTC in SignalWire - troubleshooting media negotiation
Slides PDF The World Game (s) Eco Economic Epochs.pdf
An introduction to the IFRS (ISSB) Stndards.pdf
CHE NAA, , b,mn,mblblblbljb jb jlb ,j , ,C PPT.pptx
Digital Literacy And Online Safety on internet
INTERNET------BASICS-------UPDATED PPT PRESENTATION
Introduction to the IoT system, how the IoT system works
isotopes_sddsadsaadasdasdasdasdsa1213.ppt
artificial intelligence overview of it and more
June-4-Sermon-Powerpoint.pptx USE THIS FOR YOUR MOTIVATION
Decoding a Decade: 10 Years of Applied CTI Discipline
innovation process that make everything different.pptx
Tenda Login Guide: Access Your Router in 5 Easy Steps
Introduction about ICD -10 and ICD11 on 5.8.25.pptx
Unit-3 cyber security network security of internet system
Cloud-Scale Log Monitoring _ Datadog.pdf
APNIC Update, presented at PHNOG 2025 by Shane Hermoso
E -tech empowerment technologies PowerPoint
The Internet -By the Numbers, Sri Lanka Edition
How to Ensure Data Integrity During Shopify Migration_ Best Practices for Sec...
WebRTC in SignalWire - troubleshooting media negotiation
Ad

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