generate PHP classes from XSD? [closed] - php

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 10 months ago.
Improve this question
Is there in the world analogues of JavaBeans or JAXB for PHP?
Is it possible to generate PHP classes from XML schema?
It's common practice to publish API's as XSD schemas. Java and C# guys can get advantage of this by generating classes right from XSD. Is there same tool for PHP?

I'm working now on this issue and going to release the tool as soon as it reaches more-less stable state. Check here https://web.archive.org/web/20111026063725/http://mikebevz.com/xsd-to-php-tool/
Upd. I've just release first working prototype, it works fine with UBL 2.0 schemas and one simple schema, but more serious testing is on the way. I'd appreciate if you send schemas you're working with, so I'd include them in the test suite.
Upd. 2. XSD2PHP reached version 0.0.5. Check the progress on https://github.com/moyarada/XSD-to-PHP

The main reasons for using XSD class generators is to
Get compile time checking
An easier syntax than plain old XML API's
Auto completion in your IDE.
Now contrast this with PHP. PHP does not have compile time checking and it has support for dynamic methods/properties. This voids two of the main reasons above and makes this a non-issue unless you really need auto completion. In other words, there is reason to use an XSD class generator in PHP, and that is probably also why none exist.
My suggestion is to use PHPs Simple XML which creates properties to match the XML dynamically during runtime. If you validate your XML against the XSD file and then create a Simple XML object, you have your XML object structure complete with methods and properties, without having to generate code. A perfectly good approach in PHP.
Note that I don't state that SimpleXML is the same as generated XSD classes, of course not.. But it is pretty close, usage and API-wise. You still end up doing something like $company->employee[2]->firstname either way.

This seems to do a decent job https://github.com/goetas-webservices/xsd2php
I wish it handled enumeration validation, but seemed to work ok in my use case. I found the META .yml files it generates helpful.

XSD schemas are usually written in WSDL files on SOAP Web Services.
wsdl2php is a tool for parsing WSDL(XSD) schemas to php classes. It uses php's native SoapClient as it's client:
https://github.com/jbarciauskas/wsdl2php

This library seems to be the best choice nowadays:
https://github.com/goetas/xsd2php
It generates PHP classes for XML Elements and can convert it back and forth:
XML -> PHP -> XML

I looked into that a while ago, and I certainly could not find one. If your schema is simple, there's a guy who hacked a simple version together for flat schemas.
That's all I know about. Normally these guys are good at supporting languages other than the main ones, but they don't do PHP either.

The DMS Software Reengineering Toolkit is configurable code generation machinery, that can be used to process arbitrary formal documents as input. DMS can be used to generate
code in arbitary output languages.
We have used it to generate native Java and COBOL XML readers and writers from DTDs, which are the elder cousin of schemas. The same ideas would be easily applied to PHP.

There is another recent tool called PiBX a JiBX inspired tool.
From the site:
PiBX is an XML-Data-Binding framework for PHP.
With PiBX you can generate PHP classes based off an available
XML-Schema. These classes can be used to marshal the informations to
XML without hassling with schema checks, constraints or restrictions.

Related

PHP vs OO PHP - Which one to use? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
I'm developing a web system using regular PHP. This was my first experience with PHP so the code is not legible nor clean. It mixes some HTML code with PHP.
I'd say I have already done half of the code.
What are the real advantages of the Object-oriented PHP?
The website is about books and book authors, using MySQL and Apache. So it's not a very complicated website.
The real advantage of object-orientation: your code is better organized, easier to maintain, more modular (and thus easier to reuse), and potentially less brittle (because of encapsulation of state and implementation, and hopefully better security). (The cynic in me also says that if you learn object-oriented PHP, you take the first important step to leaving the PHP ghetto. Heh. Worked for me!)
There's already a lot of questions from PHPers moving into OO on Stack Overflow:
PHP Object Oriented or Not?
Is my PHP code object oriented?
Learning PHP Class
Not to mention that there are zillions of PHP object-oriented tutorials out there. My take: basically, yes, if you are writing PHP, you should probably be writing object-oriented PHP for anything beyond the most trivial of applications. There are lots of Rails-like frameworks for PHP that will make your life easier, and may help you become a better programmer.
Object oriented PHP does not differ with the procedural style in the amount of HTML code you mingle with PHP code. So if your only concern is the mix you should look for other ways to get your code cleaned. For example you can create html template files with placeholders for your dynamic content and use file_get_contents and str_replace to inject the dynamic content at run time.
In my mind, we PHPers can thoroughly throw away the concept of Object (class instance), we only need Array and Mode Class:
All arrays in initial mode support any array function as its method:
<?php
$array1->array_flip(this);
?>
Use "->mode()" to validate the minimal data set, and then switch mode class:
<?php
$array1->mode('class1', $success);
?>
Any mode class has no "->construct()" in it, but has "->validate()" to validate the minimal data set.
The array in a mode still could use array function as its method, but after using any of them the array will be switched back into basic array mode,
and we need to use "->mode('class1', $success);" to switch mode back.
The radical thought here is data-centric programming; we need to separate the data (array) and the activity (class method).
We could modify the PHP engine, to get rid of parts of OO (object oriented), and support Mode Class. We could call it MyPHP.
For example:
$array_man1 could be set into two modes: cls_normal_man and cls_crazy_man:
<?php
$array_man1->mode('cls_normal_man')->normal_method1()->mode('cls_crazy_man')->crazy_method1();
?>
if you really want to use oo programming go to Ruby.
OO PHP for me is a fake. And if you already have half of code done in structural php dont change your mind.
just remember to make code clean with lots of comments so you can easily change sth in the future

Text mining with PHP [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 7 years ago.
Improve this question
I'm doing a project for a college class I'm taking.
I'm using PHP to build a simple web app that classify tweets as "positive" (or happy) and "negative" (or sad) based on a set of dictionaries. The algorithm I'm thinking of right now is Naive Bayes classifier or decision tree.
However, I can't find any PHP library that helps me do some serious language processing. Python has NLTK (http://www.nltk.org). Is there anything like that for PHP?
I'm planning to use WEKA as the back end of the web app (by calling Weka in command line from within PHP), but it doesn't seem that efficient.
Do you have any idea what I should use for this project? Or should I just switch to Python?
Thanks
If you're going to be using a Naive Bayes classifier, you don't really need a whole ton of NL processing. All you'll need is an algorithm to stem the words in the tweets and if you want, remove stop words.
Stemming algorithms abound and aren't difficult to code. Removing stop words is just a matter of searching a hash map or something similar. I don't see a justification to switch your development platform to accomodate the NLTK, although it is a very nice tool.
I did a very similar project a while ago - only classifying RSS news items instead of twitter - also using PHP for the front-end and WEKA for the back-end. I used PHP/Java Bridge which was relatively simple to use - a couple of lines added to your Java (WEKA) code and it allows your PHP to call its methods. Here's an example of the PHP-side code from their website:
<?php
require_once("http://localhost:8087/JavaBridge/java/Java.inc");
$world = new java("HelloWorld");
echo $world->hello(array("from PHP"));
?>
Then (as someone has already mentioned), you just need to filter out the stop words. Keeping a txt file for this is pretty handy for adding new words (they tend to pile up when you start filtering out irrelevant words and account for typos).
The naive-bayes model has strong independent-feature assumptions, i.e. it doesn't account for words that are commonly paired (such as an idiom or phrase) - just taking each word as an independent occurrence. However, it can outperform some of the more complex methods (such as word-stemming, IIRC) and should be perfect for a college class without making it needlessly complex.
You can also use the uClassify API to do something similar to Naive Bayes. You basically train a classifier as you would with any algorithm (except here you're doing it via the web interface or by sending xml documents to the API). Then whenever you get a new tweet (or batch of tweets), you call the API to have it classify them. It's fast and you don't have to worry about tuning it. Of course, that means you lose the flexibility you get by controlling the classifier yourself, but that also means less work for you if that in itself is not the goal of the class project.
Try open calais - http://viewer.opencalais.com/ . It has api, PHP classes and many more. Also, LingPipe for this task - http://alias-i.com/lingpipe/index.html
you can check this library https://github.com/Dachande663/PHP-Classifier very straight forward
you can also use thrift or gearman to deal with nltk

Generating PHP code documentation with Sphinx? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
Sphinx is a Python library to generate nice documentation from a set of ReST formatted text files. Not the tool used for full-text searching
I'm also fully aware of doxygen / phpdoc tools. I'm trying to figure out if there is a way of using Sphinx to document PHP projects? Or even any other non-Python languages?
https://www.sphinx-doc.org/en/master/
Sphinx and ReST can be used as generic documentation tools, in my experience. There's nothing about Sphinx which obligates you to only use it for Python-based projects. For example, in my work, I've used it to build a user guide and an XML-RPC API reference. In both cases, I had no use for sphinx.ext.autodoc or other Python-specific extras. The documentation was written "by hand," with mostly generic ReST directives, rather than the specialty directives provided by Sphinx. For what it's worth, I have not yet needed to create a custom ReST directive for non-Python documentation.
Even if you're working with a PHP project, I think you'll find Sphinx useful. For example most of the directives provided by the module specific markup are actually quite general. I don't see why you couldn't or wouldn't use these constructs to document stuff from languages other than Python. Likewise, Sphinx makes it pretty easy to show code examples in other languages. There's even a configuration value to change the default to any language which Pygments supports (which includes PHP). If you're feeling particularly ambitious, you could even create a Sphinx extension to pluck something relevant from your PHP code.
All that said, be sure to consider the audience for your documentation project. While I think Sphinx is an excellent tool and would recommend it for a wide range of documentation projects, if your audience is expecting something else, be mindful of that. For example, if you were documenting a Java project, much of your audience may be expecting Javadoc-style documents. If you deviate from that expectation, make sure it's not just for kicks (i.e., it gives you better docs than you'd get otherwise) and be prepared to (briefly) make the case for what you've done differently (e.g. with a FAQ answer or introduction).
Finally, any documentation is better than no documentation, regardless the tool used to create them. Use any tool that helps you, if it's the difference between getting something out there and not.
Just released a few days ago:
http://mark-story.com/posts/view/sphinx-phpdomain-released
CakePHP is using Sphinx for its new documentation, and I wrote the phpdomain for sphinx. While there isn't a way to automatically include your php doc blocks into sphinx, I still think its one of the better documentation authoring tools available. Its great for more narrative style documentation. But with the phpdomain you can make api docs as well.
The Doctrine project, an ORM for PHP, uses Sphinx to generate their online documentation at www.doctrine-project.org. They use a custom pygment for PHP. The documentation is available on Github at https://github.com/doctrine/orm-documentation. It includes the custom PHP pygment css file.
Also the python-pygments package comes with many pygment styles which you can try out by changing the pygments_style = value in your sphinx conf.py configuration file. For example, to try out the pastie highlighting sytle, which is part of python-pygments, you use
pygments_sytle = 'pastie'
As far as I'm concerned, you can document just about any syntax in Sphinx as far as you doesn't limit yourself with languages supported by autodoc. You can create beautiful API References using standard Sphinx directives like .. class, .. method, .. function and other. They work perfectly apart from the source code and doesn't require any automatic generation and linking to the sources.
You can also create generic admonitions with some special class, that you could later hook to CSS:
.. admonition Title
:class: Ololo
This text could be formatted any way you want, using the ``Ololo`` tag.
There are also roles (they allow custom classes too) and other means of adding text with some special formatting, if the original directives aren't sufficient to you.
If you decide to create your docs async from the source code, make sure you disable checking the code coverage and other code-related features in your conf.py or on project initiation.
PS: You can see a very good answer on elements with custom classes here.

PHP UML Generator [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 5 years ago.
Improve this question
How do I generate UML diagram based on existing classes in PHP?
There's also the PHP UML tool available from pear.
PHP_UML:
Can generate UML/XMI files in version 1.4, or in version 2.1 (logical, component, and deployment views)
Can generate an API documentation in HTML format
Can generate PHP code (code skeleton) from a given XMI file
Can convert UML/XMI content from version 1.4 to version 2.1
Install it on the command line via:
$ pear install pear/php_uml
(This used to be $ pear install pear/php_uml-alpha but the package has since gone stable.)
Generate your xmi:
$ phpuml -o project.xmi
I strongly recommend BOUML which:
is extremely fast (fastest UML tool ever created, check out benchmarks),
has rock solid PHP import and export support (also supports C++, Java, Python)
is multiplatform (Linux, Windows, other OSes),
is full featured, impressively intensively developed (look at development history, it's hard to believe that such fast progress is possible).
supports plugins, has modular architecture (this allows user contributions, looks like BOUML community is forming up)
phUML
phUML is fully automatic UML class diagramm generator written in PHP, licensed under the BSD license. It is capable of parsing any PHP5 object oriented source code and create an appropriate image representation of the oo structure based on the UML specification.
./phuml -r /var/www/my_project -graphviz -createAssociations false -neato out.png
Step by step guide
the best (Windows) software i have found to do PHP and UML is Sparx Systems Enterprise Architect. besides a pletora of features, it supports the following for PHP:
Reverse engineer object oriented PHP into UML class diagrams
Generate PHP class definitions from UML class diagrams
Synchronize changes made in a UML class into the corresponding PHP class definition
Synchronize changes made in a PHP class definition into the corresponding UML class
Create UML sequence diagrams to show what PHP classes use and how they are used
Produce detailed documentation of your PHP code in standard RTF and HTML format
Perform code engineering on models to generate base PHP pages.
not free ($199), but definitely worth the money.
Have you tried Autodia yet? Last time I tried it it wasn't perfect, but it was good enough.
There's also php2xmi. You have to do a bit of manual work, but it generates all the classes, so all you have to do is to drag them into a classdiagram in Umbrello.
Otherwise, generating a diagram with the use of reflection and graphviz, is fairly simple. I have a snippet over here, that you can use as a starting point.
Here's how I did it (directly from code to PDF drawing without manual drawing of anything):
Use BOUML for "reverse engineering PHP code" [sic] to extract the class model (BOUML is available from "universe" repository of Ubuntu). I seriously recommend BOUML for this step because it's really fast compared to many other programs I have tried. In addition, it seems that BOUML seems to extract the model correctly (for the parts that BOUML even tries to extract).
Use BOUML to export model as XMI 1.4 file
Use ArgoUML to import said XMI file (you can use webstart version for this step)
Export XMI from ArgoUML (I don't know which XMI version/variant the output is but it is not the same result as the output from BOUML. The argouml-graphviz cannot handle XMI file directly from BOUML).
Use argouml-graphviz to convert ArgoUML exported XMI file to dot format (you may need to use saxon instead of xsltproc to get it work due to use of XSLT2)
Use dot or fdp or sfdp to render the class diagram.
Here's an example of suitable command line for using fdp to output PDF diagram (assuming that dot file generated by argouml-graphviz XLST processing is saved as xmi-model.dot):
fdp -Tpdf -Gmaxiter=1000 -Gmindist=0.5 -Gpackmode=node \
-Eweight=0.05 -Elen=1.0 -Eminlen=1.0 -Gsplines=true \
-Goverlap=false xmi-model.dot -oxmi-model.pdf
As an alternative you could try PHP_UML or php2xmi instead of BOUML for doing the "reverse engineering" part. I haven't yet tried that.
(I'm using the phrase "reverse engineering" because it seems that UML people are using those words when they mean extracting class and method information from the source code. I would personally interpret those words as extracting information from executable binary file or captured raw wire data.)
If you prefer drawing the class diagram by hand (instead of using computer to do all the drawing), you can use either BOUML or ArgoUML for the drawing. Using the "reverse engineered" data via BOUML will help in that case.
If you are looking to generate UML easily from your existing PHP Classes you might want to consider PHPStorm 3.0 IDE. It does a good job of replicating existing code into UML.
Have a look at the PHP Storm feature list.
In theory you can use PhpStorm to visualise your classes using UML. The generation is not really great but you can effectively refactor stuff and again, at least preview parents, implementations, constants, attributes, methods and their visibility in a nice way.
Situation
I want to visualise a communication between already existing components to a colleague.
Process using PHPStorm
https://blog.jetbrains.com/phpstorm/2017/09/uml-diagrams-in-phpstorm-2017-2/
Advantages
Nice UI, final diagram.
Able to refactor code from a diagram.
Able to add notes.
The class diagram symbolises private/public properties, constructors, methods nicely.
Disadvantages
No support for PHP 7.
Painfully to use. Can't resize the generated boxes.
When adding a new relation, the previous ones get randomly lost :O wtf?
Restarting PhpStorm destroys the diagrams
Changed my mind, impossible to use relations
Result
Anyway, after some painful hour of work I was only able to generate unrelated boxes and had to use additional program to link relations. Really bad. But I believe once they make it work properly it will be a great feature because as the code changes, the diagrams would be automatically updated!
For now, don't use PhpStorm for UML diagrams.
You can use Visual Paradigm for UML. This might not be the best paid (it's US$699) product, just as an option if anyone would like to try. It can create class diagram from PHP and vice versa, and not only PHP, there's a bunch of language you can choose such as C#, C++, Ruby, Java, VB.NET, Python, Objective C, Perl, etc. There's also a trial you can check on.
Well to be honest, first and foremost you shouldn't generate UML model from code, but code from UML model ;).
Even if you are in a rare situation, when you need to do this reverse engineering, it is generally suggested that you do it by hand or at least tidy-up the diagrams, as auto-generated UML has really poor visual (=information) value most of the time.
If you just need to generate the diagrams, it's probably a good thing to ask yourself why exactly? Who is the intended audience and what is the goal? What does the auto-generated diagram have to offer, what code doesn't?
Basicly I accept only one answer to that question. It just got too big and incomprehensible.
Which again is a reason to start with UML in the first place, as opposed to start coding ;) It's called analysis and it's on decline, because every second guy in business thinks it's a bit too expensive and not really necessary.

What are best practices for developing consistent libraries? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
I am working on developing a pair of libraries to work with a REST API. Because I need to be able to use the API in very different settings I'm currently planning to have a version in PHP (for web applications) and a second version in Python (for desktop applications, and long running processes). Are there any best practices to follow in the development of the libraries to help maintain my own sanity?
So, the problem with developing parallel libraries in different languages is that often times different languages will have different idioms for the same task. I know this from personal experience, having ported a library from Python to PHP. Idioms aren't just naming: for example, Python has a good deal of magic you can use with getters and setters to make object properties act magical; Python has monkeypatching; Python has named parameters.
With a port, you want to pick a "base" language, and then attempt to mimic all the idioms in the other language (not easy to do); for parallel development, not doing anything too tricky and catering to the least common denominator is preferable. Then bolt on the syntax sugar.
'Be your own client' : I've found that the technique of writing tests first is an excellent way of ensuring an API is easy to use. Writing tests first means you will be thinking like a 'consumer' of your API rather than just an implementor.
Try to write a common unit test suite for both. Maybe by wrapping a class in one language for calling it from the other. If you can't do it, at least make sure the two versions of the tests are equivalent.
Well, the obvious one would be to keep your naming consistent. Functions and classes should be named similarly (if not identically) in both implementations. This usually happens naturally whenever you implement an API separately in two different languages. The big ticket item though (at least in my book) is to follow language-specific idioms. For example, let's assume that I were implementing a REST API in two languages I'm more familiar with: Ruby and Scala. The Ruby version might have a class MyCompany::Foo which contains method bar_baz(). Conversely, the Scala version of the same API would have a class com.mycompany.rest.Foo with a method barBaz(). It's just naming conventions, but I find it goes a long way to helping your API to feel "at home" in a particular language, even when the design was created elsewhere.
Beyond that I have only one piece of advise: document, document, document. That's easily the best way to keep your sanity when dealing with a multi-implementation API spec.
AFAIKT there are a lot of bridges from to scripting languages. Let's take e.g Jruby, it's Ruby + Java, then there are things to embed Ruby in Python (or the other way). Then there are examples like Etoile where the base is Objective-C but also bridges to Python and Smalltalk, another approach on wide use: Wrapping C libraries, examples are libxml2, libcurl etc etc. Maybe this could be the base. Let's say your write all for Python but do implement a bridge to PHP. So you do not have that much parrallel development.
Or maybe it's not the worst idea to base that stuff let's say on .NET, then you suddenly have a whole bunch of languages to your disposal which in principal should be usable from every other language on the .NET platform.
why not use python for web applications too? there are several frameworks available: django, web2py - similar to django but many say it's simpler to use, there is also TurboGears, web.py, Pylons
along the lines of bridging - you could use interprocess communication to have PHP and python application (in daemon mode) talk to each other.

Categories