A cleaner way to go with my controller method - php

I am making an app that translates a word from one language to English and gets information about it (e.g. definition, use in a sentence, synonyms, sound representation)
What my function does:
Searches for the translation in the database. If it is found, we return it.
If it is not found we translate a word using google translate, or Yandex translate API.
If translation is found we download it's sound representation, save the translation to the database and add additional information from other API's
We return a json response with all of the information.
Now my controllers method is really big and I can't find a cleaner way to go about it.
Any help is appreciated.
public function store(Request $request)
{
$translated = $request->get('translated');
$translation = $this->translation->findBy('translated', $translated)->first();
if ($translation) {
return Response::json(['translation' => $this->translation->with(['examples', 'definitions', 'synonyms', 'images'])->find($translation->id)], ResponseCode::HTTP_CREATED);
}
$data = $request->all();
$data['translation'] = $this->translate($translated);
if ($translated == $data['translation']) {
Log::info('Translation not found: ' . $data['translation']);
return $this->translationNotFound();
}
$downloader = new Downloader(new GoogleSpeechDownloader());
$filename = $downloader->download($data['translation']);
if ($filename) $data['sound_name'] = $filename;
$translation = $this->translation->create($data);
$this->createDefinition($translation);
$this->createExample($translation);
$this->createSynonym($translation);
return Response::json(['translation' => $this->translation->with(['examples', 'definitions', 'synonyms', 'images'])->find($translation->id)], ResponseCode::HTTP_CREATED);
}
private function translationNotFound()
{
return Response::json(['error' => 'Vertimas nerastas.'], ResponseCode::HTTP_NOT_FOUND);
}
private function createDefinition($translation)
{
$definition = new Definition();
$definer = new Definer(new DictionaryApiDefiner());
try {
$definition->definition = $definer->getDefinition($translation->translation);
$definition->approved = true;
$translation->definitions()->save($definition);
} catch (\Exception $e) {
Log::alert('Definition for word ' . $translation->translation . ' not found.');
}
}
private function createExample($translation)
{
$example = new Example();
$exampler = new ExampleCreator(new YourDictionaryGouteParserExampler());
try {
$example->example = $exampler->getExample($translation->translation);
$example->approved = true;
$translation->examples()->save($example);
} catch (\Exception $e) {
Log::alert('Example for word ' . $translation->translation . ' not found.');
}
}
private function createSynonym($translation)
{
$creator = new SynonymCreator(new BigHugeLabsSynonymCreator());
foreach ($creator->getSynonyms($translation->translation) as $s) {
$synonym = new Synonym();
$synonym->synonym = $s;
$synonym->approved = true;
$translation->synonyms()->save($synonym);
}
}
private function translate($translated)
{
$translator = new Translator(new GoogleTranslator());
try {
return $translator->translate($translated);
} catch (\Exception $e) {
Log::critical($e->getMessage());
}
$translator = new Translator(new YandexTranslator());
return $translator->translate($translated);
}

If you want cleaner code, just make a class for this job. Two classes for this two API's and in the controller make the check for the word, if not exist in the database, check in the other two API's, just split every action to method in the new two classes that you will make.

Related

PHP - ZF2 - render template from string variable

i have problem with rendering template in ZF2, where template is in string in variable. There is simple example:
$template = "<div>easy</div>";
$view = new \Zend\View\Model\ViewModel();
$view->setTemplate($template);
$renderer = new \Zend\View\Renderer\PhpRenderer();
$html = $renderer->render($view);
This code fail on rendering, the renderer think that the template is a path to file. And iam reallz not sure how to tell rendere its a string.
Thx for your time and respond.
You have to extend the PhpRenderer class and override the render method, in such a way that will use the string in the $template as the actual template:
class MyPhpRenderer extends PhpRenderer {
public function render($nameOrModel, $values = null)
{
if ($nameOrModel instanceof Model) {
$model = $nameOrModel;
$nameOrModel = $model->getTemplate();
if (empty($nameOrModel)) {
throw new Exception\DomainException(sprintf(
'%s: received View Model argument, but template is empty',
__METHOD__
));
}
$options = $model->getOptions();
foreach ($options as $setting => $value) {
$method = 'set' . $setting;
if (method_exists($this, $method)) {
$this->$method($value);
}
unset($method, $setting, $value);
}
unset($options);
// Give view model awareness via ViewModel helper
$helper = $this->plugin('view_model');
$helper->setCurrent($model);
$values = $model->getVariables();
unset($model);
}
// find the script file name using the parent private method
$this->addTemplate($nameOrModel);
unset($nameOrModel); // remove $name from local scope
$this->__varsCache[] = $this->vars();
if (null !== $values) {
$this->setVars($values);
}
unset($values);
// extract all assigned vars (pre-escaped), but not 'this'.
// assigns to a double-underscored variable, to prevent naming collisions
$__vars = $this->vars()->getArrayCopy();
if (array_key_exists('this', $__vars)) {
unset($__vars['this']);
}
extract($__vars);
unset($__vars); // remove $__vars from local scope
while ($this->__template = array_pop($this->__templates)) {
$this->__file = $this->resolver($this->__template);
try {
if (!$this->__file) {
$this->__content = $this->__template; // this line does what you need
}else{
ob_start();
$includeReturn = include $this->__file;
$this->__content = ob_get_clean();
}
} catch (\Exception $ex) {
ob_end_clean();
throw $ex;
}
if ($includeReturn === false && empty($this->__content)) {
throw new Exception\UnexpectedValueException(sprintf(
'%s: Unable to render template "%s"; file include failed',
__METHOD__,
$this->__file
));
}
}
$this->setVars(array_pop($this->__varsCache));
if ($this->__filterChain instanceof FilterChain) {
return $this->__filterChain->filter($this->__content); // filter output
}
return $this->__content;
}
}
and then you code should look like:
$template = "<div>easy</div>";
$view = new \Zend\View\Model\ViewModel();
$view->setTemplate($template);
$renderer = new MyPhpRenderer();
$html = $renderer->render($view);
Try by replacing '\' with _ underscore as Zend_View_Renderer_PhpRenderer

How to save embedded forms in symfony 1?

I have a form which represnts single answer object (this is standard propel generated form I have not changed much there only some validation rules) and another form that represents a collection of answers code as below:
class BbQuestionAnswersForm extends sfForm {
public function __construct($defaults = array(), $options = array(), $CSRFSecret = null) {
parent::__construct($defaults, $options, $CSRFSecret);
}
public function configure() {
if (!$questions = $this->getOption('questions')) {
throw new InvalidArgumentException('The form need array of BbExamQuestion objects.');
}
if (!$taker = $this->getOption('taker')) {
throw new InvalidArgumentException('The form need BbExamtaker object.');
}
if (!$user = $this->getOption('questions')) {
throw new InvalidArgumentException('The form need sfGuardUser object.');
}
foreach($questions as $question) {
$answer = new BbExamAnswer();
$answer->setBbExamQuestion($question);
$answer->setBbExamTaker($taker);
$answer->setCreatedBy($user);
$answer->setUpdatedBy($user);
$form = new BbExamAnswerForm($answer, array('question' => $question));
$this->embedForm($question->getId(), $form);
}
$this->widgetSchema->setNameFormat('solve[%s]');
}
}
Everything(validation, display) goes fine with this form until I try to save it. Part of action which trying to save the form:
...
$this->form = new BbQuestionAnswersForm(null, array('questions' => $this->questions, 'taker' => $this->taker, 'user' => $this->getUser()->getGuardUser()));
if($request->isMethod('post')) {
$this->form->bind($request->getParameter($this->form->getName()));
if($this->form->isValid()) {
if($this->form->save()) {
$this->getUser()->setFlash('success', 'Save goes fine.');
$this->redirect($this->generateUrl('#bb'));
} else {
$this->getUser()->setFlash('error', 'Upps an error occurred.');
}
}
}
When I send valid form I receive "Call to undefined method BbQuestionAnswersForm::save()" error.
I tried to write this method like this:
public function save() {
$conn = Propel::getConnection(ZlecPeer::DATABASE_NAME);
$conn->beginTransaction();
try{
foreach($this->getEmbeddedForms() as $form) {
$form->save();
}
$conn->commit();
} catch(Exception $e) {
$conn->rollback();
echo 'upps something goes wrong';
die($e->getMessage());
return false;
}
return true;
}
but it doesnt work, I receive exception without any message.
What am I doing wrong, how to make save method work?
I believe your BbQuestionAnswersForm is extending the wrong object. It should extend BaseFormDoctrine or possibly BaseBbQuestionAnswersForm if you are using the framework correctly.
Edit: Just noticed you are using propel but it should be the same thing. Try:
class BbQuestionAnswersForm extends BaseBbQuestionAnswersForm
and less likely:
class BbQuestionAnswersForm extends BaseFormPropel
Save method should looks like this:
public function save($con = null) {
if (null === $con) {
$con = Propel::getConnection(BbExamAnswerPeer::DATABASE_NAME);
}
$con->beginTransaction();
try{
foreach($this->embeddedForms as $name => $form) {
if(!isset($this->values[$name]) || !is_array($this->values[$name])) {
continue;
}
if($form instanceof sfFormObject) {
$form->updateObject($this->values[$name]);
$form->getObject()->save($con);
$form->saveEmbeddedForms($con);
} else {
throw new Exception('Embedded form should be an instance of sfFormObject');
}
}
$con->commit();
} catch(Exception $e) {
$con->rollBack();
throw $e;
return false;
}
return true;
}

CakePHP - call_user_func_array() looses $this->request->data?

I need to call Controller-methods dynamically. For this purpose I wrote the following code:
if(isset($method['postParams'])) {
foreach($method['postParams'] as $index => $param) {
$this->request->data[ $index ] = $param;
}
}
App::import('Controller', $method['controller']);
// get result
$method['controller'] = $method['controller'] . 'Controller';
$Controller = new $method['controller']();
try {
if(count($method['params'])) {
$varVal = call_user_func_array(array($Controller, $method['method']), $method['params']);
} else {
$varVal = call_user_func(array($Controller, $method['method']));
}
} catch(Exception $e) {
$varVal = $e;
}
$this->set($varName, $varVal);
Now I debug the function being called and see that $this->request->data is NULL.
How to solve this?
For the sake of completeness I'll post the answer to this problem for anyone having a similar issue to find the solution more easily.
Instead of:
$this->request->data
Use:
$Controller->request->data
After instanciating the $Controller object.

PHP pass an object via a function

I have this function that returns a json object:
function getMyFbEvents() {
global $facebook;
try {
$fb_events = $facebook->api('/me/events/');
foreach ($fb_events["data"] as $fb_event_data) {
$event_info = json_decode(file_get_contents('https://graph.facebook.com/' . $fb_event_data['id'] . '/?access_token=' . $facebook->getAccessToken()));
return $event_info;
}
} catch (FacebookApiException $e) {
error_log($e);
$fb_events = null;
return null;
}
}
Now if I want to call that object from another page of the script by calling the relative function, how do I do it?
I mean if I want to loop now $event_info as if it I was inside that function and get each given data, is there a way?
Maybe it may sound a bit "too much" :)
First of instead of returning from within the loop you need to accumulate all of the values then return
function getMyFbEvents() {
global $facebook;
try {
$fb_events = $facebook->api('/me/events/');
$eventDetails = array();
foreach ($fb_events["data"] as $fb_event_data) {
$event_info = json_decode(file_get_contents('https://graph.facebook.com/' . $fb_event_data['id'] . '/?access_token=' . $facebook->getAccessToken()));
$eventDetails[] = $event_info;
}
return $eventDetails;
} catch (FacebookApiException $e) {
error_log($e);
$fb_events = null;
return null;
}
}
Then when you want to use it just say (make sure you include_once the file that implements getMyFbEvents if it is in a different php file.)
$events = getMyFbEvents();
forearch($events as $event){
echo $event->description;
}
On a side note using the global keyword is considered bad practice. A cleaner implementation would just pass in the $facebook variable as a parameter to the function
function getMyFbEvents($facebook) {
try {
//..... the rest of your function
Then to call just
$var = getMyFbEvents($facebook);

Creating helper for my application

I have been creating a helper class for the Facebook PHP API in order to avoid reusing a lot of code. The helper works but the only problem is that its very slow.. and I also figured out why! when I initialize the class, the constructor is called twice! I checked in my code and the other elements which use this class only call it once (It's something inside the class itself) Could you please help me figure out what the problems could be?? Thanks!
class FbHelper
{
private $_fb;
private $_user;
function __construct()
{
// Initalize Facebook API with keys
$this->_fb = new Facebook(array(
'appId' => 'xxxxxxxxxxx',
'secret' => 'xxxxxxxxxxxxxxxxxxxxxx',
'cookie' => true,
));
// set the _user variable
//
$this->doLog("Called Constructor");
//
$this->_user = $this->UserSessionAuthorized();
return $this;
}
function doLog($text)
{
// open log file <----- THIS GETS CALLED TWICE EVERY TIME I INITIALIZE THE CLASS!!
$filename = "form_ipn.log";
$fh = fopen($filename, "a") or die("Could not open log file.");
fwrite($fh, date("d-m-Y, H:i")." - $text\n") or die("Could not write file!");
fclose($fh);
}
function getUser() { return $this->_user; }
function getLoginUrl() { return $this->_fb->getLoginUrl(); }
function getLogoutUrl() { return $this->_fb->getLogoutUrl(); }
function UserSessionAuthorized()
{
// Checks if user is authorized, if is sends back user object
$user = null;
$session = $this->_fb->getSession();
if (!$session) return false;
try {
$uid = $this->_fb->getUser();
$user = $this->_fb->api('/me');
if ($user) return $user;
else return false;
}
catch (FacebookApiException $e) { return false; }
}
private function _rebuildSelectedFriends($selected_friends)
{
// Creates a new array with less data, more useful and less malicious
$new = array();
foreach ($selected_friends as $friend)
{
$f = array('id' => $friend['id'], 'name' => $friend['name']);
$new[] = $f;
}
return $new;
}
function GetThreeRandomFriends()
{
$friends = $this->_fb->api('/me/friends');
$n = rand(1, count($friends['data']) - 3);
$selected_friends = array_slice($friends['data'], $n, 3);
return $this->_rebuildSelectedFriends($selected_friends);
}
function UserExists($user_id)
{
try { $this->_fb->api('/' . $user_id . '/'); return true; }
catch (Exception $e) { return false; }
}
}
You must be calling the FbHelper class twice as your doLog function is in the constructor, therefore the repetition is somewhere higher up in your application and not in this class itself.

Categories