Ankündigung

Einklappen
Keine Ankündigung bisher.

PHP-Klassen generieren

Einklappen

Neue Werbung 2019

Einklappen
X
  • Filter
  • Zeit
  • Anzeigen
Alles löschen
neue Beiträge

  • Scriptangebot PHP-Klassen generieren

    Muss gerade wieder ein DB-Schema in PHP-Klassen umdrücken. Der Generator hilft dabei etwas.

    Klassenname eingeben & Spaltentypen + Namen, Ergebnis: PHP-Klasse. Der Zend-Generatorkram war mir dafür zu oversized, brauchte ein schnelles Standalone-Skript.

    Vielleicht brauchts ja wer irgendwann (z.B. ich)

    Code:
    <?php
    error_reporting(E_ALL | E_STRICT);
    ini_set("display_errors", 1);
    ?>
    <form action="" method="post">
        <label>Class</label>:
        <input type="text" name="class" value="<?php echo @$_REQUEST["class"]; ?>" />
        <hr />
    <?php
    $count = 1;
    if (!empty($_REQUEST)):
        $count = count($_REQUEST["name"]);
    endif;
    for ($i = 0; $i < $count; ++$i):
    ?>
        <div class="section">
            <label>Typ</label>:
            <select name="type[]">
    <?php
    foreach (array("uint", "int", "bool", "string", "datetime") as $type):
        $selected = $_REQUEST["type"][$i] === $type;
        printf(
            '%s<option value="%s"%s>%s</option>%s',
            str_repeat(' ', 12),
            $type,
            $selected ? ' selected="selected"' : '',
            $type,
            PHP_EOL
        );
    endforeach;
    ?>
            </select>
            <label>Name</label>:
            <input name="name[]" type="text" value="<?php echo @$_REQUEST["name"][$i]; ?>" />
            <input type="button" onclick="return removeSection(this)" value="-" />
            <input type="button" onclick="return moveSectionUp(this)" value="hoch" />
            <input type="button" onclick="return moveSectionDown(this)" value="runter" />
            <hr />
        </div>
    <?php
    endfor;
    ?>
        <input type="button" value="+" onclick="return addSection()" />
        <input type="submit" />
        <input type="reset" onclick="return confirmReset()" />
    </form>
    <hr />
    <?php
    if (!empty($_REQUEST)):
        highlight_string('<?php' . PHP_EOL . GenerateCode::generateStatic($_REQUEST));
    endif;
    ?>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
    <script type="text/javascript">
    
    function addSection()
    {
        var newSectionJ = $('.section:first').clone(true);
        var lastSectionJ = $('.section:last').after(newSectionJ);
        newSectionJ.find('input[type=text]').val('');
        return false;
    }
    
    function removeSection(elem)
    {
        var sectionJ = $(elem).parents('.section:first');
        var sectionCount = $('.section').length;
        if (sectionCount <= 1) {
            return false;
        }
        sectionJ.remove();
        return false;
    }
    
    function confirmReset()
    {
        if (confirm('Reset?')) {
            location.reload(true);
        }
        return false;
    }
    
    function moveSectionUp(elem)
    {
        var buttonJ = $(elem);
        var sectionJ = buttonJ.parents('.section:first');
        var prevSectionJ = sectionJ.prev();
        if (prevSectionJ.is('hr')) {
            return false;
        }
        sectionJ.insertBefore(prevSectionJ);
        return false;
    }
    
    function moveSectionDown(elem)
    {
        var buttonJ = $(elem);
        var sectionJ = buttonJ.parents('.section:first');
        var nextSectionJ = sectionJ.next();
        if (nextSectionJ.is('input')) {
            return false;
        }
        sectionJ.insertAfter(nextSectionJ);
        return false;
    }
    
    </script>
    <?php
    class GenerateCode
    {
        protected $_className;
        protected $_elements = array();
    
        public static function generateStatic(array $data)
        {
            $generateCode = new self();
            $generateCode->setClassName($data["class"]);
            $generateCode->setElementsByRequest($data);
            return $generateCode->generate();
        }
    
        public function setClassName($className)
        {
            $this->_className = $className;
        }
    
        public function setElementsByRequest(array $data)
        {
            $count = count($data["name"]);
            for ($i = 0; $i < $count; ++$i) {
                $name = $data["name"][$i];
                $type = $data["type"][$i];
    
                if (empty($name)) {
                    break;
                }
    
                $key = $name;
                $name = $this->_getCamelCase($key);
    
                $declaration = '$_' . $name;
                $usage       = '$this->_' . $name;
                $set         = 'set' . ucfirst($name);
                $get         = 'get' . ucfirst($name);
                $has         = 'has' . ucfirst($name);
                $variable    = '$' . $name;
    
                switch ($type) {
                    case "uint":
                        $realType = 'int';
                        $setBody  = <<<PHP
            $variable = (int)$variable;
            if ($variable < 1) {
                $variable = null;
            }
            $usage = $variable;
    PHP;
                        break;
                    case "int":
                        $realType = $type;
                        $setBody  = <<<PHP
            if ($variable !== null) {
                $variable = (int)$variable;
            }
            $usage = $variable;
    PHP;
                        break;
                    case "bool":
                        $realType = $type;
                        $setBody  = <<<PHP
            if ($variable !== null) {
                $variable = (bool)$variable;
            }
            $usage = $variable;
    PHP;
                        break;
                    case "string":
                        $realType = $type;
                        $setBody  = <<<PHP
            $variable = (string)$variable;
            $variable = trim($variable);
            if ($variable === "") {
                $variable = null;
            }
            $usage = $variable;
    PHP;
                        break;
                    default:
                        throw new Exception("invalid element type ($type)");
                }
    
                $this->_elements[] = compact(
                    "key",
                    "name",
                    "type",
                    "declaration",
                    "usage",
                    "set",
                    "setBody",
                    "get",
                    "has",
                    "variable",
                    "realType"
                );
            }
        }
    
        public function generate()
        {
            $className = $this->_className;
            $package = $this->_getPackageName($className);
            $properties = $this->generateProperties();
            $propertyMethods = $this->generatePropertyMethods();
            $commonMethods = $this->generateCommonMethods();
            $code = <<<PHP
    /**
     * content of class $className
     *
     * SVN information:
     * @since   \$Date\$
     * @version \$Revision\$
     * @author  \$Author\$
     */
    /**
     * $className
     *
     * @package $package
     * @author  <NAME>
     */
    class $className
    {
    $properties
    
    $propertyMethods
    
    $commonMethods
    }
    PHP;
            return $code;
        }
    
        public function generateProperties()
        {
            $code = "";
            foreach ($this->_elements as $element) {
                extract($element);
                $code .= <<<PHP
        /**
         * @var $realType
         */
        protected $declaration;
    
    
    PHP;
            }
            return rtrim($code);
        }
    
        public function generatePropertyMethods()
        {
            $code = "";
            foreach ($this->_elements as $element) {
                extract($element);
                $code .= <<<PHP
        /**
         * @param  $realType $variable
         * @return null
         */
        public function $set($variable)
        {
    $setBody
        }
    
        /**
         * @return $realType
         */
        public function $get()
        {
            return $usage;
        }
    
        /**
         * @return bool
         */
        public function $has()
        {
            return $usage !== null;
        }
    
    
    PHP;
            }
            return rtrim($code);
        }
    
        public function generateCommonMethods()
        {
            $code = <<<PHP
        /**
         * @param  array
         * @return null
         */
        public function fromArray(array \$data)
        {
    
    PHP;
            foreach ($this->_elements as $element) {
                extract($element);
                $code .= <<<PHP
            if (array_key_exists("$key", \$data)) {
                \$this->$set(\$data["$key"]);
            }
    
    PHP;
            }
            $code .= <<<PHP
        }
    
        /**
         * @return array
         */
        public function toArray()
        {
            \$data = array(
    
    PHP;
            foreach ($this->_elements as $element) {
                extract($element);
                $code .= <<<PHP
                "$key" => \$this->$get(),
    
    PHP;
            }
            $code = rtrim($code);
            $code = rtrim($code, ",");
            $code .= <<<PHP
    
            );
            return \$data;
        }
    PHP;
            return rtrim($code);
        }
    
        protected function _getCamelCase($key)
        {
            $key = strtolower($key);
            $splits = explode("_", $key);
            $first  = array_shift($splits);
            $splits = array_map("ucfirst", $splits);
            array_unshift($splits, $first);
            $name = implode("", $splits);
            return $name;
        }
    
        protected function _getPackageName($className)
        {
            $splits = explode("_", $className);
            $packageName = array_shift($splits);
            return $packageName;
        }
    }
    Ausgabe (My_Test, id (uint), label (string)):
    Code:
    <?php 
    /**
     * content of class My_Test
     *
     * SVN information:
     * @since   $Date$
     * @version $Revision$
     * @author  $Author$
     */
    /**
     * My_Test
     *
     * @package My
     * @author  <NAME>
     */
    class My_Test
    {
        /**
         * @var int
         */
        protected $_id;
    
        /**
         * @var string
         */
        protected $_label;
    
        /**
         * @param  int $id
         * @return null
         */
        public function setId($id)
        {
            $id = (int)$id;
            if ($id < 1) {
                $id = null;
            }
            $this->_id = $id;
        }
    
        /**
         * @return int
         */
        public function getId()
        {
            return $this->_id;
        }
    
        /**
         * @return bool
         */
        public function hasId()
        {
            return $this->_id !== null;
        }
    
        /**
         * @param  string $label
         * @return null
         */
        public function setLabel($label)
        {
            $label = (string)$label;
            $label = trim($label);
            if ($label === "") {
                $label = null;
            }
            $this->_label = $label;
        }
    
        /**
         * @return string
         */
        public function getLabel()
        {
            return $this->_label;
        }
    
        /**
         * @return bool
         */
        public function hasLabel()
        {
            return $this->_label !== null;
        }
    
        /**
         * @param  array
         * @return null
         */
        public function fromArray(array $data)
        {
            if (array_key_exists("id", $data)) {
                $this->setId($data["id"]);
            }
            if (array_key_exists("label", $data)) {
                $this->setLabel($data["label"]);
            }
        }
    
        /**
         * @return array
         */
        public function toArray()
        {
            $data = array(
                "id" => $this->getId(),
                "label" => $this->getLabel()
            );
            return $data;
        }
    }

  • #2
    Ich brauch das jetzt nicht akut, aber top, dass du sowas hier freigibst, danke.

    Kommentar


    • #3
      wieso kann man im Zeitalter von Social Media nicht Einträge liken?

      Sehr gut, danke fürs teilen.

      Kommentar


      • #4
        Zitat von ph|L Beitrag anzeigen
        wieso kann man im Zeitalter von Social Media nicht Einträge liken?

        Sehr gut, danke fürs teilen.
        Bewerte das Thema..

        Kommentar

        Lädt...
        X