- Symfony's convenience methods for automatically fetching database entities from URL parameters are super-handy.
- Obfuscated/hash IDs are a great idea, especially in APIs (where you aren't concerned with SEO, but might be concerned about sequential numeric ids or exposing database information).
- Here's how to make them work together.
The stuff in this gist sets up a Twig filter (obfuscate
) to create the obfuscated ids (for URLs), makes the obfuscator available as a service (id_obfuscator
) so you can also generate obfuscated URLs in your controllers or whatever, and extends the DoctrineParamConverter to allow it to retrieve entities by their deobfuscated id.
Following Phil Sturgeon's excellent advice in Build APIs You Won't Hate, I've also added an option to allow multiple ids to be loaded at once, like /resources/id1,id2,id3,id4
. It's really quite handy sometimes. Bewarned though; it won't 404 if only some of the ids are missing. Of this whole thing, this is the part that could do with the most attention, sorry! The good news is that it's totally optional, so if you want to avoid the potential shonkiness then just don't use it. In the example controller code I put separate actions to demonstrate how you use it with and without multiple-id support, but obviously don't use both, that's just silly. Pick one! If you don't like to read and just paste the code in, it'll crash. That's my petty vengeance at work :)
I've used Zack Kitzmiller's Tiny-php library here because it's simple and great, but you could use hashids instead with very little change; same difference.
Take it, use it (at your own risk), fix it, no need to credit me. I'm not sure it warrants clogging up Packagist with, but if you do decide to make it into a reusable Symfony bundle then I'd love to know about it.
- sf2.6 has an
app/config/services.yml
file, while if you started your project with an earlier version you probably don't. You can make your own and import it toconfig.yml
or you could just put this stuff in there directly, whatever. - sf2.6 starts new projects with an AppBundle, following the Symfony Best Practices, while older versions don't (and actually make it kind of an arse to set one up, since it has no vendor namespace). Just… use whatever you're already using I guess.
- Read APIs you won't hate again to remember how to handle 404s with multiple ids
- Support for different Tiny keys (e.g. for different entities)
- Add tests
- Make it a Bundle