Search code examples
phppluralize

How to handle pluralisation in PHP


I have an app, presumably an API, which I am working on. The app returns in JSON format for the requested resources. So I have a project management application, where the structure is similar to what is below:

  • Projects
    • Payments
    • Issues
      • Discussion
  • Users

Now the API will give calls to:

/projects                List all the projects
/project                 List all the projects (alias)
/projects/ID/issues      List all the issues of this project
/project/ID/issues       List all the issues of this project (alias)
/projects/ID/issue       List all the issues of this project (alias)
/project/ID/issue        List all the issues of this project (alias)

And so on. Now the problem for me is, I would be using switch ($request) for this and I have crazy case statements like below:

<?php
  switch ($request) {
    case '/projects':
    case '/project':
      # code...
      break;

    case '/projects/ID/issues':
    case '/project/ID/issues':
    case '/projects/ID/issue':
    case '/project/ID/issue':
      # code...
      break;
  }

I hope you understood the problem. Think about the number of cases for the discussion part. It would be exponentially higher. That would go by combination of the 3 values, which will come to 2 to the power of 3 (23) which comes around 8 case statements.

Is there a best way to reduce this? This is my first time in Stack Overflow. Thanks in advance.


Solution

  • You can reduce it by checking in the first attempt. i.e., check for the plural or singular form, and replace it with one single form.

    <?php
      $request = replace(array("projects", "project"), "project", $request);
      $request = replace(array("issues", "issue"), "issue", $request);
      $request = replace(array("users", "user"), "user", $request);
      $request = replace(array("discussions", "discussion"), "discussion", $request);
    

    And later check in the switch () case for just the singular form:

    <?php
      switch ($request) {
        case '/project':
          # code...
          break;
    
        case '/project/ID/issue':
          # code...
          break;
      }
    

    I know this would be a repetitive task, but I guess if you don't want to use any pluralisation methods, this is better. Hope this "quick hack" is helpful. Since you don't have more than three or four variables, this is better.

    Note: The main reason I gave this answer is for Simplicity and for not using RegEx.