generate PHP classes from XSD?

后端 未结 8 2139
春和景丽
春和景丽 2020-12-05 07:41

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

8条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-05 07:58

    The main reasons for using XSD class generators is to

    1. Get compile time checking
    2. An easier syntax than plain old XML API's
    3. 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.

提交回复
热议问题