DWX2015 Code Generierung

588 views

Published on

Mit dem Zend Framework 2 können Sie als Entwickler nicht nur komplexe Webanwendungen und Webservices umsetzen. Der integrierte Code-Generator ist ein praktisches Werkzeug, um lästige Aufgaben bei der Einrichtung neuer Projekte automatisieren zu können. Kombiniert mit einer Konsolenanwendung können Sie Ihr eigenes RAD-Tool (Rapid-Application-Development) aufsetzen, das nicht allein auf die Code-Generierung für das Zend Framework 2 beschränkt ist. In dieser Session lernen Sie das Rüstzeug für den Aufbau eines solchen Tools kennen.

Published in: Internet
1 Comment
1 Like
Statistics
Notes
  • Danke für das SlideShare und die wirklich interessanten Informationen.
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
No Downloads
Views
Total views
588
On SlideShare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
2
Comments
1
Likes
1
Embeds 0
No embeds

No notes for slide

DWX2015 Code Generierung

  1. 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. 2. Über michÜber mich 2 / 59www.RalfEggert.dewww.RalfEggert.de
  3. 3. [B01] MotivationMotivation 3 / 59
  4. 4. Frage ans PublikumFrage ans Publikum 4 / 59 [b02][b02]
  5. 5. Einsatzzwecke: KonsoleEinsatzzwecke: Konsole 5 / 59 Codegenerierung DeploymentSkripte InstallationsSkripte Datenbank Migration SocketServerCron Jobs Spider / Crawler
  6. 6. [B03] ToolsTools 6 / 59
  7. 7. Tools Konsole & CodeTools Konsole & Code 7 / 59 Konsole Code
  8. 8. Tools Konsole & CodeTools Konsole & Code 8 / 59 Konsole Code
  9. 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. 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. 11. ??? BausteineBausteine 11 / 59 PHP 5.5 C0mposer ZFConsole ZendConsole ZendCode ZendConfig ZendDb ZendFilter ZendValidator
  12. 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. 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
  14. 14. [B00] ZFConsoleZFConsole 14 / 59
  15. 15. ProjektProjekt https://github.com/zfcampus/zf-console 15 / 59 [b00]
  16. 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. 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. 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. 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. 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
  21. 21. [B04] KommandosKommandos 21 / 59
  22. 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. 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. 24. KonsoleKonsole 24 / 59 $ bin/phpcg.php hello-world --------------------------------------------------------------------------- PHP Code Generator (DWX2015), version 1.0.0 Hello World ---------------------------------------------------------------------------
  25. 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. 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. 27. KonsoleKonsole 27 / 59 $ bin/phpcg.php hello-you Ralf --------------------------------------------------------------------------- PHP Code Generator (DWX2015), version 1.0.0 Hello "Ralf" ... ---------------------------------------------------------------------------
  28. 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. 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. 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
  31. 31. [B05] CODECODE GeneratorGenerator 31 / 59
  32. 32. ProjektProjekt https://github.com/zendframework/zend-code 32 / 59 [b00]
  33. 33. GeneratorenGeneratoren 33 / 59 Body Generator Class Generator Doc Block Generator FileGenerator Method Generator Parameter Generator PropertyGenerator TRAIT Generator Value Generator Weitere Generatoren
  34. 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. 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. 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. 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. 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. 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); } } ----------------------------------------------------------------------------------------
  40. 40. [B06] DatenbankDatenbank 40 / 59
  41. 41. ProjektProjekt https://github.com/zendframework/zend-db 41 / 59 [b00]
  42. 42. ZendDb KomponentenZendDb Komponenten 42 / 59 Adapter Metadata Result Set RowGateway SQL Table Gateway
  43. 43. DatenbankmodellDatenbankmodell 43 / 59
  44. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 55. [B07] War es das?War es das? 55 / 59
  56. 56. Weitere IdeenWeitere Ideen 56 / 59 Entities Aktualisieren ✓ Formulare generieren Validierung In Entity ✓ Entities löschen InputFilter Generieren
  57. 57. Fragen vom Publikum?Fragen vom Publikum? 57 / 59 [b08]
  58. 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. 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

×