CakePHP 4 - custom request and response format

72 views Asked by At

For a new project I want to use a CakePHP 4 as REST backend with a Vue.js frontend.
Now Cake uses a nested data structure while vue.js uses a flat data structure.
My plan now is to convert the data in the backend.

Example Format:

CakePHP
{
    "user": {
        "id": 1,                    
        "name": "Peter Maus"
        "articles" : [
            {
                "id": 15,
                "title": "First Post",
            }
        ]
    },
    
}

Vue.js
{
    "user": {
        "id": 1,                    
        "name": "Peter Maus"
        "articles" : [ 15 ]
    },
    "articles": [
        {
            "id": 15,
            "title": "First Post",
        }
    ]
}

So basically instead of just sending json with

$this->viewBuilder()->setOption('serialize', ['user']);  

I want to first "convert the datastructure" and then send as json.

I have now found the following possibilities for the conversion based on the documentation:

Request - convert from vue to cake
I have seen that you can use Body Parser Middleware with your own parser. But I still have json as response format and I don't want to override the standard json formatter.

Response - convert from cake to vue
ideas:

  • I have seen "Data Views", but I'm not sure if it is suitable for this purpose.

  • extend the ViewBuilder and write my own serialize() function.
    How would I have to include my own ViewBuilder, is that even possible?

  • write a parser function in a parent entity from which all my entities inherit. And call that parse function before serializing the data.

I will probably need access to the Entity Relations to dynamically restructure the data, for both: request and response.
What would be a reasonable approach?

0

There are 0 answers