11.22
In Framework , PHP5 , Propel , Server-Side , Symfony | Tags: backend, json, PHP5, propel, Symfony, task
JSON is a perfect way to use an object in backend and frontend.
Here, I’m gonna create a Symfony task to modify your table models for adding toJson method. toJson method returns a JSON object from your table model.
symfony generate:task propel:add-toJson-method
Run the command above. That will create a task file into lib/tasks/propelAddtoJsonmethodTask.class.php
Edit that file via your code or text editor and find the commented line including add your code here
There’s where we are going to put our codes.
First we need to find model directory. If there is a broken link or something to get us unable to reach model directory we throw an exception.
$models = array();
$dir = realpath(dirname(__FILE__) . ‘/../model/’);
if (!is_dir($dir))
{
throw new Exception(’Unable to find model directory’);
}
If we find model directory then we need to find all model classes. Actually, to find Peer classes is fine. We won’t touch any other files. At that point, we need to aware of that we can’t modify any file under sub directories. Because they’ll be re-created at next building process. If we can’t find any file that we needed we throw an exception.
$dh = opendir($dir);
while (($file = readdir($dh)) !== false)
{
if (substr($file, -4) == ‘.php’)
{
$model = explode(’.', $file);
if (substr($model[0], -4) == ‘Peer’)
{
array_push($models, $model[0]);
}
}
}
closedir($dh);if (!count($models))
{
throw new Exception(’There is no class for any table in model directory’);
}sort($models);
In next step, we need to parse those files and find a place to put our code.
foreach ($models as $m)
{
$tablePeer = new $m();if (!method_exists($tablePeer, ‘toJson’))
{
$code = trim(file_get_contents($dir . ‘/’ . $m . ‘.php’));
if (substr($code, -2) == ‘?>’)
{
$code = trim(substr($code, 0, strlen($code) -2));
}if (substr($code, -1) != ‘}’)
{
throw new Exception($m . ‘: unable to parse’);
}$code = trim(substr($code, 0, strlen($code) -1));
$code .= “\n static public function toJson(” . ‘$obj’ . “) {\n ” . ‘return json_encode($obj->toArray());’ . “\n }\n”;
$code .= “}\n”;file_put_contents($dir . ‘/’ . $m . ‘.php’, $code);
}
}
Now, we can call our task in command line:
symfony propel:add-toJson-method
Click here to see source code.
Also, you can use Propel Behaviors in Symfony to perform that. Documentation is online at http://www.symfony-project.org/cookbook/1_2/en/behaviors
Comments are closed.