Welcome Guest, Not a member yet? Register   Sign In
Roster: Relation Name Lookup
#1

Hi all- I have some "dynamite" for you: small package, big impact! "Roster" solves a common, niche problem in an elegant way: quick access to display names for entity relations without requiring database lookup.
Tatter\Roster
Bulk name lookup for database relations in CodeIgniter 4
Packagist: https://packagist.org/packages/tatter/roster
GitHub: https://github.com/tattersoftware/codeigniter4-roster

An example to demonstrate how it works... You are developing a blog. At the bottom of every post is a comments section where logged in users may post replies. In order to display the user names next to each comment you need to cross-reference your "comments" table with the "users" table. You can:
  • Query the database with a JOIN to get all the info in one transaction, then parse it out later
  • Use an Object Relation Mapping (ORM) solution that makes entities "aware" of their related components
  • Load all the relevant users separately in the Controller then link them together
  • All of the above come with a performance cost, so you will need to include a way to cache the result so it does not affect every page.
Enter `Tatter\Roster`. A Roster class is a pre-defined mapping of table IDs to their "display name". The Roster service handles all the loading, lookup, and caching for you so you can be assured of the best performance for the least code.

Here's what your Roster looks like for Users, in app/Rosters/UserRoster.php:
PHP Code:
namespace App\Rosters;

use 
App\Models\UserModel;
use 
Tatter\Roster\ModelRoster;

class 
UserRoster extends ModelRoster
{
protected 
$modelName UserModel::class;
protected 
$field    'username';


The Roster Service handles locating your Roster and matching the ID, so you can use it inline right in your HTML:
Code:
<?php foreach ($comments as $comment): ?>
<div class="comment">
    <blockquote><?= $comment->content ?></blockquote>
    <div class="comment-footer">
        Commented by <?= service('roster')->user($comment->user_id) ?>
    </div>
</div>
<?php endforeach; ?>


That's all! As always check out the docs, give it a try, and send over any feedback you have.
Reply


Messages In This Thread
Roster: Relation Name Lookup - by MGatner - 09-28-2021, 08:43 AM
RE: Roster: Relation Name Lookup - by InsiteFX - 09-29-2021, 03:50 AM
RE: Roster: Relation Name Lookup - by paliz - 09-30-2021, 02:54 AM
RE: Roster: Relation Name Lookup - by includebeer - 10-05-2021, 03:37 PM
RE: Roster: Relation Name Lookup - by MGatner - 10-07-2021, 04:54 AM
RE: Roster: Relation Name Lookup - by includebeer - 10-07-2021, 06:12 AM



Theme © iAndrew 2016 - Forum software by © MyBB