Last active
December 17, 2015 02:49
-
-
Save AmyStephen/5538748 to your computer and use it in GitHub Desktop.
Translations with Anonymous Function
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Molajo; | |
{ | |
/** Translation Class */ | |
class Language implements LanguageInterface | |
{ | |
public function translate($key) | |
{ | |
if ($key == 'h') { | |
return 'Hello'; | |
} else { | |
return 'Goodbye'; | |
} | |
} | |
} | |
/** Concrete Class */ | |
class Test | |
{ | |
protected $language; | |
public function __construct($language) | |
{ | |
$this->language = $language; | |
} | |
public function t($key) | |
{ | |
$t = $this->language; | |
return $t($key); | |
} | |
public function doThisThing() | |
{ | |
$message = 'ABC ' . $this->t('h') . ' ZYZ.'; | |
return $message; | |
} | |
} | |
/** Anonymous Function */ | |
$t = function ($request) { | |
$class = 'Molajo\\Language'; | |
$language = new $class(); | |
$value = $language->translate($request); | |
return $value; | |
}; | |
/** Pass in the Translation Function */ | |
$class = 'Molajo\\Test'; | |
$test = new $class($t); | |
$thing = $test->doThisThing(); | |
echo $thing; | |
} |
Excellent. Oh boy! There is some very big potential for interoperability. I've been hoping you might be thinking that way. =)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Yeah, I've had these same debates in my mind.
I've actually toyed with the idea of creating a "contracts" package that was nothing but interfaces - no implementation, which would then be used by most other packages. That gets you a common library of "contracts" without having to depend on all the implementation, etc. I do have a "Contracts" namespace in the Laravel 4 "support" package which is used by all other packages which is similar to that idea. I did something like this in my .NET days by creating a DLL that was strictly interfaces and it worked out pretty well for us. I still think that is a pretty good approach to dealing with this issue in PHP.
Anyways, something to think about.