Skip to content
Advertisement

Is it possible to load Swagger annotations from a different class or file?

I have the following simple PHP method like the following

/**
*
* (swagger annotation to be called from a different class)
*
*/
public function getApiCall()
{
  //Do something
}

and I need to include long Swagger documentation into the annotation above the method, so
is it possible to write the annotation in a different class ? and call it here with something like

/**
*
*call('AppHttpControllerstestAnnotation');
*/

The main purpose is to have a clean class without so many lines of documentation and annotations in it.

Advertisement

Answer

Loading “annotations from a different class” is not something that makes a lot of sense. Annotations are read in the annotated code, that’s their whole purpose.

But if you want to keep configuration and code separated, you do not have to use Swagger-Php to generate your swagger configuration file.

The package is simply a convenience way to generate the swagger.json file from code annotations.

But if you do not want to use annotations in the first place, and keep your classes clean from extraneous configuration (something that I personally applaud), just… do not use Swagger-Php and build your own configuration files outside of your classes.

You could even write it in YAML, if you feel more comfortable than writing JSON by hand. For example::

openapi: 3.0.0
info:
  title: 'Search API'
  version: 1.0.0
servers:
- url: 
  description: Current host server
- url: https:your-server.com
  description: Prod server
paths:
  /foo:
    post:
      summary: 'Creates a new foo'
      description: 'Builds a new Foo and makes it available to Bar'
      requestBody:
        description: 'Foo '
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/Foo'
      responses:
        '201':
          description: Foo created
        '202':
          description: Foo queued, it will be eventually created.
components:
  schemas:
    Foo:
      type: object
      required:
      - name
      - size
      properties:
        name:
          type: string
        size:
          type: integer

This, once converted to JSON (there are many libraries to do this, or you could even use a free service like this one), you can feed the resulting JSON to swagger directly.

E.g. the YAML above parses to this JSON file. You can easily test it out by heading to the Swagger demo instance, and past the JSON URL in the “explore” location bar, and you’ll get something like this:

enter image description here

In the end, it’s not much more work than using annotations (if any more work at all), and you can keep your entity classes clean from configuration concerns.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement