Skip to content

Make TranslatorExtension extendable #354

Closed

Description

@daun

Explain your intentions

I'd like to extend a custom TranslatorExtension from Latte's built-in one. I mainly need to encapsulate the translator function in a class, so that consumers can just do new CustomTranslator() without having to pass in a callback themselves. Like below. Unfortunately, this is currently impossible as TranslatorExtension is marked as final.

class CustomTranslator extends \Latte\TranslatorExtension
{
    public function __construct() {
      parent::__construct([$this, 'translate']);
    }

    public function translate($key, $data = null, $lang = null) {
        return app()->translate($key, $data, $lang);
    }
}

Make a strong case of the merits of this feature

I'm assuming there's no specific reason the class can't be extendable. If one wanted to do this, one would have to re-implement all the useful features inside it, like the _ tag and the |translate filter.

Activity

  1. dg commented on Nov 20, 2023

    @dg
    Member

    This is not an optimal use of inheritance. It is better to use either composition or, better yet, factory:

    class CustomTranslatorFactory
    {
        public static function create() {
          return new Latte\TranslatorExtension([self::class, 'translate']);
        }
    
        public static function translate($key, $data = null, $lang = null) {
            return app()->translate($key, $data, $lang);
        }
    }
    
    
    $latte->addExtension(CustomTranslatorFactory::create());
  2. locked and limited conversation to collaborators on Nov 20, 2023
  3. converted this issue into a discussion #355 on Nov 20, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions