PHP entity class generator - php
I am creating entity (of entity-view-controller)(in other words, model of MVC) classes which theoreticlly match the databse table I have. Is there a tool which reads mysql table and creates a model class code? (NOT on execution, a code output is required)
I expect an output like
class{
public $columnname1;
public $columnname2;
public $columnname3;
public $columnname4;
public $columnname5;
public $columnname6;
function __construct(&$columnname1, &$columnname2){...}
function insert(&$columnname1, &$columnname2){}
function delete(&$columnname1){}
...
}
A tool which would also create insert,update and delete by id functions would help me a lot.
The tool may be free or paid.
PDO can fetch results into an object.
Design a class which matches your database/query structure, and use PDO::FETCH_INTO to fetch the result set into an already instantiated object. Misread the question, my bad.
To generate the class itself from the database structure, there are several projects (I haven't tested, but this came up on a very simple search).
db2php
PHP MySQL class generator
The following code is what I've used for a long time to create PHP models for MySQL and DB2 tables. I've got stubs in place for MSSQL, PGSQL and SQLite but have never needed to complete them.
Here's the code generator class:
<?php
/**
* #license http://opensource.org/licenses/MIT The MIT License
* #version 1.0.0_20130220000000
*/
/**
* This class will generate PHP source code for a "model" that interfaces with
* a database table.
*
* #license http://opensource.org/licenses/MIT The MIT License
* #version 1.0.0_20130220000000
*/
class db_code_generator{
private $closing_tag;
private $columns;
private $database;
private $host;
private $password;
private $port;
private $table;
private $type;
private $username;
/**
* Constructor. By default we will try to connect to a MySQL database on
* localhost.
*
* #param string $database The name of the database the user wants to connect
* to.
*
* #param string $table The name of the table to generate code for.
*
* #param string $username The username we should use to connect to the
* database.
*
* #param string $password The password we need to connect to the database.
*
* #param string $host The host or server we will try to connect to. If the
* user doesn't give us a host we default to localhost.
*
* #param string $port The port we should try to connect to. Typically this
* will not be passed so we default to NULL.
*
* #param string $type The type of database we are connecting to. Valid
* values are: db2, mssql, mysql, pgsql, sqlite.
*/
public function __construct($database = NULL,
$table = NULL,
$username = NULL,
$password = NULL,
$host = 'localhost',
$type = 'mysql',
$port = NULL,
$closing_tag = TRUE){
$this->database = $database;
$this->table = $table;
$this->username = $username;
$this->password = $password;
$this->host = $host;
$this->port = $port;
$this->type = $type;
$this->closing_tag = $closing_tag;
}
/**
* Generate the code for a model that represents a record in a table.
*
* #return string The PHP code generated for this model.
*/
public function get_code(){
$this->get_data_definition();
$code = $this->get_file_head();
$code .= $this->get_properties();
$code .= $this->get_ctor();
$code .= $this->get_dtor();
$code .= $this->get_method_stubs();
$code .= $this->get_file_foot();
return $code;
}
/**
* Create the code needed for the __construct function.
*
* #return string The PHP code for the __construct function.
*/
private function get_ctor(){
$code = "\t/**\n";
$code .= "\t * Constructor.\n";
$code .= "\t *\n";
$code .= "\t * #param mixed \$id The unique id for a record in this table. Defaults to NULL\n";
if ('db2' === $this->type){
$code .= "\n\t * #param string \$library The library where the physical file resides. Defaults to LIBRARY\n";
}
$code .= "\t *\n";
$code .= "\t * #see base_$this->type::__construct\n";
$code .= "\t */\n";
if ('db2' === $this->type){
$code .= "\tpublic function __construct(\$id = NULL, \$library = 'LIBRARY'){\n";
$code .= "\t\tparent::__construct(\$id, \$library);\n";
}else{
$code .= "\tpublic function __construct(\$id = NULL){\n";
$code .= "\t\tparent::__construct(\$id);\n";
}
$code .= "\t}\n\n";
return $code;
}
/**
* Connect to the requested database and get the data definition for the
* requested table.
*/
private function get_data_definition(){
try{
switch ($this->type){
case 'db2':
$this->get_data_definition_db2();
break;
case 'mssql':
$this->get_data_definition_mssql();
break;
case 'mysql':
$this->get_data_definition_mysql();
break;
case 'pgsql':
$this->get_data_definition_pgsql();
break;
case 'sqlite':
$this->get_data_definition_sqlite();
break;
}
}catch(PDOException $e){
}
}
/**
* Get data definition information for a DB2 table.
*/
private function get_data_definition_db2(){
$con = new PDO("odbc:DRIVER={iSeries Access ODBC Driver};SYSTEM=$this->host;PROTOCOL=TCPIP", $this->username, $this->password);
$sql = "SELECT COLUMN_NAME, COLUMN_SIZE, COLUMN_TEXT, DECIMAL_DIGITS, ORDINAL_POSITION, TYPE_NAME FROM SYSIBM.SQLCOLUMNS WHERE TABLE_SCHEM = '". strtoupper($this->database) ."' AND TABLE_NAME = '". strtoupper($this->table) ."'";
$statement = $con->prepare($sql);
if ($statement->execute()){
while ($row = $statement->fetch()){
if (NULL !== $row['DECIMAL_DIGITS']){
$decimal = $row['DECIMAL_DIGITS'];
}else{
$decimal = NULL;
}
if ('DECIMAL' === $row['TYPE_NAME'] && NULL !== $row['DECIMAL_DIGITS'] && '0' !== $row['DECIMAL_DIGITS']){
$type = 'float';
}else if ('DECIMAL' === $row['TYPE_NAME']){
$type = 'integer';
}else{
$type = strtolower($row['TYPE_NAME']);
}
if ('1' === $row['ORDINAL_POSITION']){
$key = 'PRI';
}else{
$key = NULL;
}
$this->columns[$row['COLUMN_NAME']] = array('allow_null' => TRUE,
'decimal' => $decimal,
'default' => NULL,
'extra' => NULL,
'key' => $key,
'length' => $row['COLUMN_SIZE'],
'name' => $row['COLUMN_NAME'],
'text' => $row['COLUMN_TEXT'],
'type' => $type);
}
ksort($this->columns);
}
}
/**
* Get data definition information for a MS SQL table.
*/
private function get_data_definition_mssql(){
return "The code for generating MS SQL models is not yet implemented.\n";
}
/**
* Get data definition information for a MySQL table.
*/
private function get_data_definition_mysql(){
$dsn = "mysql:host=$this->host;";
if (NULL !== $this->port){
$dsn .= "port=$this->port;";
}
$dsn .= "dbname=$this->database";
$con = new PDO($dsn, $this->username, $this->password);
$sql = "SHOW COLUMNS FROM $this->table";
$statement = $con->prepare($sql);
if ($statement->execute()){
while ($row = $statement->fetch()){
$this->columns[$row['Field']] = array('allow_null' => $row['Null'],
'decimal' => NULL,
'default' => $row['Default'],
'extra' => $row['Extra'],
'key' => $row['Key'],
'length' => NULL,
'name' => $row['Field'],
'text' => NULL,
'type' => $row['Type']);
}
ksort($this->columns);
}
}
/**
* Get data definition information for a PostgreSQL table.
*/
private function get_data_definition_pgsql(){
return "The code for generating PostgreSQL models is not yet implemented.\n";
}
/**
* Get data definition information for a SQLite table.
*/
private function get_data_definition_sqlite(){
return "The code for generating SQLite models is not yet implemented.\n";
}
/**
* Create the code needed for the __destruct function.
*
* #return string The PHP code for the __destruct function.
*/
private function get_dtor(){
$code = "\t/**\n";
$code .= "\t * Destructor.\n";
$code .= "\t */\n";
$code .= "\tpublic function __destruct(){\n";
$code .= "\t\tparent::__destruct();\n";
$code .= "\t}\n\n";
return $code;
}
/**
* Generate the code found at the end of the file - the closing brace, the
* ending PHP tag and a new line. Some PHP programmers prefer to not have a
* closing PHP tag while others want the closing tag and trailing newline -
* it probably just depends on their programming background. Regardless it's
* best to let everyone have things the way they want.
*/
private function get_file_foot(){
$code = '';
if ($this->closing_tag){
$code .= "}\n?>\n";
}else{
$code .= '}';
}
return $code;
}
/**
* Generate the code found at the beginning of the file - the PHPDocumentor
* doc block, the require_once for the correct base class and the class name.
*
* #return string The code generated for the beginning of the file.
*/
private function get_file_head(){
$code = "<?php\n";
$code .= "/**\n";
$code .= " * Please enter a description of this class.\n";
$code .= " *\n";
$code .= " * #author XXX <XXX#domain.com>\n";
$code .= " * #copyright Copyright (c) ". date('Y') ."\n";
$code .= " * #license http://www.gnu.org/licenses/gpl-3.0.html GPLv3\n";
$code .= " * #version ". date('Ymd') ."\n";
$code .= " */\n\n";
$code .= "require_once('base_$this->type.php');\n\n";
$code .= "class ". strtolower($this->table) ." extends base_$this->type{\n";
return $code;
}
/**
* Generate the code for a delete method stub.
*
* #return string The PHP code for the method stub.
*/
private function get_method_stub_delete(){
$code = "\t/**\n";
$code .= "\t * Override the delete method found in the base class.\n";
$code .= "\t *\n";
$code .= "\t * #param mixed \$id The unique record ID to be deleted.\n";
$code .= "\t *\n";
$code .= "\t * #return bool TRUE if a record was successfully deleted from the table, FALSE otherwise.\n";
$code .= "\t */\n";
$code .= "\tpublic function delete(\$id){\n";
$code .= "\t\treturn parent::delete(\$id);\n";
$code .= "\t}\n\n";
return $code;
}
/**
* Generate the code for an insert method stub.
*
* #return string The PHP code for the method stub.
*/
private function get_method_stub_insert(){
$code = "\t/**\n";
$code .= "\t * Override the insert method found in the base class.\n";
$code .= "\t *\n";
$code .= "\t * #param array \$parms An array of data, probably the \$_POST array.\n";
$code .= "\t * #param bool \$get_insert_id A flag indicating if we should get the autoincrement value of the record just created.\n";
$code .= "\t *\n";
$code .= "\t * #return bool TRUE if a record was successfully inserted into the table, FALSE otherwise.\n";
$code .= "\t */\n";
$code .= "\tpublic function insert(\$parms, \$get_insert_id = FALSE){\n";
$code .= "\t\treturn parent::insert(\$parms, \$get_insert_id);\n";
$code .= "\t}\n\n";
return $code;
}
/**
* Generate the code for an update method stub.
*
* #return string The PHP code for the method stub.
*/
private function get_method_stub_update(){
$code = "\t/**\n";
$code .= "\t * Override the update method found in the base class.\n";
$code .= "\t *\n";
$code .= "\t * #param array &\$parms An array of key=>value pairs - most likely the \$_POST array.\n";
$code .= "\t *\n";
$code .= "\t * #param integer \$limit The number of records to update. Defaults to NULL.\n";
$code .= "\t *\n";
$code .= "\t * #return bool TRUE if a record was successfully updated, FALSE otherwise.\n";
$code .= "\t */\n";
$code .= "\tpublic function update(\$parms, \$limit = NULL){\n";
$code .= "\t\treturn parent::update(\$parms, \$limit);\n";
$code .= "\t}\n\n";
return $code;
}
/**
* Create method stubs for create, delete and update.
*
* #return string The PHP code for these stubs.
*/
private function get_method_stubs(){
$code = $this->get_method_stub_delete();
$code .= $this->get_method_stub_insert();
$code .= $this->get_method_stub_update();
return $code;
}
private function get_properties(){
$code = '';
if (count($this->columns)){
foreach ($this->columns AS $index => $col){
$code .= "\t/**\n";
if (NULL !== $col['text']){
$code .= "\t * $col[text]\n";
}else{
$code .= "\t * Description\n";
}
$code .= "\t * #var ". $col['type'];
if (NULL !== $col['length']){
$code .= " ($col[length]";
if (NULL !== $col['decimal']){
$code .= ",$col[decimal]";
}
$code .= ")";
}
$code .= "\n\t */\n";
$temp_name = str_replace('#', '_', $col['name']);
$code .= "\tpublic \$$temp_name;\n\n";
}
}
return $code;
}
}
?>
and here's a simple page to use it:
<?php
/**
* #license GPLv3 (http://www.gnu.org/licenses/gpl-3.0.html)
* #version 1.0.0_20130220000000
*/
require_once('db_code_generator.php');
$table_type = array();
$table_type['db2'] = 'DB2/400 (db2)';
$table_type['mssql'] = 'Microsoft SQL Server (mssql)';
$table_type['mysql'] = 'MySQL (mysql)';
$table_type['pgsql'] = 'PostGRESQL (pgsql)';
$table_type['sqlite'] = 'SQLite (sqlite)';
$database = (isset($_POST['database'])) ? $_POST['database'] : 'my_database';
$host = (isset($_POST['host'])) ? $_POST['host'] : 'localhost';
$username = (isset($_POST['username'])) ? $_POST['username'] : 'root';
$password = (isset($_POST['password'])) ? $_POST['password'] : '';
$table = (isset($_POST['table'])) ? $_POST['table'] : '';
$type = (isset($_POST['type'])) ? $_POST['type'] : 'mysql';
$library = (isset($_POST['library'])) ? $_POST['library'] : 'LIBRARY';
$file = (isset($_POST['file'])) ? $_POST['file'] : 'STATES';
//---------------------------------------------------------------------------
?>
<div class="data_input">
<form action="" method="post">
<fieldset class="top">
<legend>Code Generator</legend>
<label for="host">Hostname or IP:
<input id="host" maxlength="32" name="host" tabindex="<?php echo $tabindex++; ?>" title="Enter the database host name" type="text" value="<?php echo $host; ?>" />
</label>
<br />
<label for="username">Username:
<input id="username" maxlength="32" name="username" tabindex="<?php echo $tabindex++; ?>" title="Enter the database username" type="text" value="<?php echo $username; ?>" />
</label>
<br />
<label for="password">Password:
<input id="password" maxlength="32" name="password" tabindex="<?php echo $tabindex++; ?>" title="Enter the database password" type="password" value="<?php echo $password; ?>" />
</label>
<br />
<label for="type">Type:
<select id="type" name="type" tabindex="<?php echo $tabindex++; ?>">
<?php
foreach ($table_type AS $key=>$value){
echo('<option ');
if ($key == $type){
echo 'selected="selected" ';
}
echo 'value="'. $key .'">'. $value .'</option>';
}
?>
</select>
</label>
<br />
</fieldset>
<fieldset class="top">
<legend>PostGRESQL/MSSQL/MySQL Parameters</legend>
<label for="database">Database:
<input id="database" maxlength="100" name="database" tabindex="<?php echo $tabindex++; ?>" title="Enter the database name" type="text" value="<?php echo $database; ?>" />
</label>
<br />
<label for="table">Table:
<input id="table" maxlength="100" name="table" tabindex="<?php echo $tabindex++; ?>" title="Enter the table name" type="text" value="<?php echo $table; ?>" />
</label>
<br />
</fieldset>
<fieldset class="top">
<legend>DB2 Parameters</legend>
<label for="library">Library:
<input id="library" maxlength="10" name="library" tabindex="<?php echo $tabindex++; ?>" title="Enter the library name" type="text" value="<?php echo $library; ?>" />
</label>
<br />
<label for="file">Physical File:
<input id="file" maxlength="10" name="file" tabindex="<?php echo $tabindex++; ?>" title="Enter the file name" type="text" value="<?php echo $file; ?>" />
</label>
<br />
</fieldset>
<fieldset class="bottom">
<button tabindex="<?php echo $tabindex++; ?>" type="submit">Generate!</button>
</fieldset>
</form>
</div>
<?php
if (isset($_POST['host'])){
if ('db2' == $_POST['type']){
$_POST['database'] = strtoupper($_POST['library']); // Library
$_POST['table'] = strtoupper($_POST['file']); // Physical file
$_POST['host'] = 'db2_host';
$_POST['username'] = 'db2_username';
$_POST['password'] = 'db2_password';
}
$object = new db_code_generator($_POST['database'], $_POST['table'], $_POST['username'], $_POST['password'], $_POST['host'], $_POST['type']);
echo('<textarea rows="75" style="margin-left : 50px; width : 90%;" onfocus="select()">'. $object->get_code() .'</textarea>');
}
?>
I understand you're looking for a ORM kind of a thing.
hope this helps
http://www.doctrine-project.org/
http://propelorm.org/
What about symfony? It does exactly what you say and you get a beastly good framework to go with it.
symfony 'compiles' classes for you based on a data model that you supply. It will make sure that compiled classes and MySQL database structure are in sync.
This approach is favorable over a Reflection based approach as it's simply too slow.
For what it's worth, Rafael Rocha shares code here.
Still, I strongly propose to use an ORM. Transforming MySQL structure back to a database-abstraction layer is anything but good...
Try this
https://github.com/rcarvello/mysqlreflection
A useful utility I built for the Object Relation Mapping of MySQL databases.
The utility generates automatically PHP classes for any tables of a given database schema.
The package is extracted from my personal PHP Web MVC Framework.
Yes, Doctrine is what you need.
Run a command, and you get all your tables' metadata in XML or YML format(choice is yours)
$ php app/console doctrine:mapping:convert xml ./src/Bundle/Resources/config/doctrine/metadata/orm --from-database --force
Once you generate the Metadata, command Doctrine to import the schema to build related entity classes you need. You will find all GET and SET functionality(read SELECT, UPDATE and INSERT) inside.
1.$ php app/console doctrine:mapping:import Bundle annotation
2.$ php app/console doctrine:generate:entities Bundle
Read details with Example here
Fat free framework allows you to work with existing tables using code like:
$user=new DB\SQL\Mapper($db,'users');
// or $user=new DB\Mongo\Mapper($db,'users');
// or $user=new DB\Jig\Mapper($db,'users');
$user->userID='jane';
$user->password=md5('secret');
$user->visits=0;
$user->save();
The code above creates new record in users table
I have written a PHP code which will automatically detect all the databases in MYSQL database, on selecting any of the database all of its related tables are loaded. You can select all the tables or any respective table to generate the Modal Class.
The following is the link to my repository
https://github.com/channaveer/EntityGenerator
This will automatically create Entity folder and dump all the entity class into that folder.
NOTE - Currently only supported for MYSQL
Hope it helps. Happy Coding!
I think you should make itout on your on. Every project and requirement of Model Code is different in my opinion. Two mysql queries will keep you in ease.
SHOW TABLES FROM db_NAME //this gives the table listing, so its Master Looper
DESC tbl_name //detail query that fetches column information of given table
DESC tbl_name will give Field, Type, Null, Key, Default and Extra Columns.
e.g. values seperated in pipes (|):
Id | int(11) | NO | PRI | NULL | auto_increment |
I followed these to make Model, controller and Viewer files supporting CRUD operation in Codeigniter 2 way back. It worked just fine.
Related
How to handle checkbox values in a query string?
I have a query string that has a bunch of form field values in it. One of the fields is a checkbox and it creates duplicate parameters, for example: ?employee_selection_needs=cat&employee_selection_needs=dog&employee_selection_needs=pig I need to place all of these checkbox values into one variable to be submitted to the HubSpot API. How can I accomplish that? I've tried it with a foreach loop but that does not seem to work. $firstname = $_POST["firstname"]; $lastname = $_POST["lastname"]; $email = $_POST["email"]; $organization_name = $_POST["organization_name"]; $phone = $_POST["phone"]; $best_describes_org = $_POST["best_describes_org"]; $organizations_safety = $_POST["organizations_safety"]; $confident_interview_process = $_POST["confident_interview_process"]; $needs_around_leadership = $_POST["needs_around_leadership"]; $used_employee_assessments = $_POST["used_employee_assessments"]; $hire_annually = $_POST["hire_annually"]; foreach($_POST['employee_selection_needs'] as $needs) { $employee_selection_needs .= $needs; } //Need to populate these variable with values from the form. $str_post = "firstname=" . urlencode($firstname) . "&lastname=" . urlencode($lastname) . "&email=" . urlencode($email) . "&phone=" . urlencode($phonenumber) . "&organization_name=" . urlencode($organization_name) . "&best_describes_org=" . urlencode($best_describes_org) . "&employee_selection_needs=" . urlencode($employee_selection_needs) . "&organizations_safety=" . urlencode($organizations_safety) . "&confident_interview_process=" . urlencode($confident_interview_process) . "&needs_around_leadership=" . urlencode($needs_around_leadership) . "&used_employee_assessments=" . urlencode($used_employee_assessments) . "&hire_annually=" . urlencode($hire_annually) . "&hs_context=" . urlencode($hs_context_json); //Leave this one be
Hei man! I'll try to answer You as easily as possible Method 1 : From Query String (Your case) Using ?employee_selection_needs=cat&employee_selection_needs=dog&employee_selection_needs=pig the PHP parser consider only last Key:Value (pig) and for this You haven't an Array to iterate It' necessary to split URL. See below <?php /** CODE */ /** Create an Array of Query Strings Values * * OUTPUT EXAMPLE * array( * 0 => 'employee_selection_needs=cat', * 1 => 'employee_selection_needs=dog', * 2 => 'employee_selection_needs=pig', * 3 => 'other_key=other_value', * ... * ) */ $queryArray= explode('&', $_SERVER['QUERY_STRING']); /** Init a variable for append Query Values */ $myOutputString = ""; /** Need for separate append values */ $myOutputToken = "|"; /** Append to $myOutputString the correct Query Value */ foreach($queryArray as $queryArrayElement) { /** Create an Array starting from a Query String * * OUTPUT EXAMPLE * array( * 0 => 'employee_selection_needs', * 1 => 'cat', * ) */ $tArray= explode('=', $queryArrayElement); /** Filter only "employee_selection_needs" key and append Query Value * to $myOutputString */ if(!empty($tArray[0]) && $tArray[0] == 'employee_selection_needs') { if(!empty($tArray[1])) $myOutputString .= $tArray[1].$myOutputToken; } } /** Remove last Token */ if(!empty($myOutputString)) $myOutputString = substr($myOutputString, 0, -strlen($myOutputToken)); print_r($myOutputString); // Expected result cat|dog|pig /** OTHER APPEND HERE */ ?> Method 2 : From HTML Form You need to use "employee_selection_needs[]" instead of "employee_selection_needs" on checkbox. See below <form ...> <input type="checkbox" value="dog" name="employee_selection_needs[]" /> <input type="checkbox" value="cat" name="employee_selection_needs[]" /> <input type="checkbox" value="fish" name="employee_selection_needs[]" /> ... </form> On submit You'll have an Array of values instead Single value <?php /** ... CODE ... */ /** Now is an array =)) */ $used_employee_assessments = $_POST["used_employee_assessments"]; /** ... CODE ... */ /** Convert to String, if You need */ $myOutputString = ""; foreach($used_employee_assessments as $assessment) $myOutputString .= $assessment; /** OR use implode ( string $glue , array $pieces ) * $myOutputString = implode(" %MY_TOKEN% ", $used_employee_assessments); */ /** OTHER APPEND HERE */ ?>
In order to pass multiple parameters with the same name you should include [] in the end of the name. So your url should look like this: ?employee_selection_needs[]=cat&employee_selection_needs[]=dog&employee_selection_needs[]=pig To do this your checkbox should have name="employee_selection_needs[]"
codeigniter - Call to a member function query() on a non-object
I'm using xampp 1.77 version, codeigniter 1.7.2 with flexigrid. I follow step by step this tutorial https://gembelzillonmendonk.wordpress.com/2010/06/28/flexigrid-and-codeigniter-with-advanced-searching-with-example/#comment-353 but I don't understand which code must have flexigrid.php in CI_Folder\system\application\controllers\flexigrid.php. My flexigrid.php code is this: <?php class Flexigrid extends Controller { function Flexigrid () { parent::Controller(); $this->load->helper('flexigrid'); } function index() { //ver lib $this->load->model('ajax_model'); $records = $this->ajax_model->get_select_countries(); $options = ''; foreach( $records as $v ) { $options .= $v['name'] . ';'; } $options = substr($options, 0, -1); /* * 0 - display name * 1 - width * 2 - sortable * 3 - align * 4 - searchable (2 -> yes and default, 1 -> yes, 0 -> no.) */ $colModel['id'] = array('ID',40,TRUE,'center',2); $colModel['iso'] = array('ISO',40,TRUE,'center',0); $colModel['name'] = array('Name',180,TRUE,'left',1); $colModel['printable_name'] = array('Printable Name',120,TRUE,'left',1,'options' => array('type' => 'date')); $colModel['iso3'] = array('ISO3',130, TRUE,'left',1, 'options' => array('type' => 'select', 'edit_options' => $options)); $colModel['numcode'] = array('Number Code',80, TRUE, 'right',1, 'options' => array('type' => 'select', 'edit_options' => ":All;AND:AND;KK:KK;RE:RE")); $colModel['actions'] = array('Actions',80, FALSE, 'right',0); /* * Aditional Parameters */ $gridParams = array( 'width' => 'auto', 'height' => 400, 'rp' => 15, 'rpOptions' => '[10,15,20,25,40]', 'pagestat' => 'Displaying: {from} to {to} of {total} items.', 'blockOpacity' => 0.5, 'title' => 'Hello', 'showTableToggleBtn' => true ); /* * 0 - display name * 1 - bclass * 2 - onpress */ $buttons[] = array('Delete','delete','test'); $buttons[] = array('separator'); $buttons[] = array('Select All','add','test'); $buttons[] = array('DeSelect All','delete','test'); $buttons[] = array('separator'); //Build js //View helpers/flexigrid_helper.php for more information about the params on this function $grid_js = build_grid_js('flex1',site_url("/ajax"),$colModel,'id','asc',$gridParams,$buttons); $data['js_grid'] = $grid_js; $data['version'] = "0.36"; $data['download_file'] = "Flexigrid_CI_v0.36.rar"; $this->load->view('flexigrid',$data); } function example () { $data['version'] = "0.36"; $data['download_file'] = "Flexigrid_CI_v0.36.rar"; $this->load->view('example',$data); } } ?> When i type http://127.0.0.1/flexiadvanced/index.php/flexigrid browser give me a error: Fatal error: Call to a member function query() on a non-object in C:\xampp\htdocs\flexiadvanced\system\application\models\ajax_model.php on line 34 this is the code of ajax_model.php <?php if (!defined('BASEPATH')) exit('No direct script access allowed'); /** * Eye View Design CMS module Ajax Model * * PHP version 5 * * #category CodeIgniter * #package EVD CMS * #author Frederico Carvalho * #copyright 2008 Mentes 100Limites * #version 0.1 */ class Ajax_model extends Model { /** * Instanciar o CI */ public function Ajax_model() { parent::Model(); $this->CI =& get_instance(); } public function get_select_countries() { //Select table name $table_name = "country"; //Build contents query $separator = (string) ','; //$this->db->select('concat(iso3, concat('. addcslashes($separator) .', iso3))')->from($table_name); $query = $this->db->query("select concat(iso3, concat(':', iso3)) as name from country where iso3 is not null"); //Get contents return $query->result_array(); } public function get_countries() { //Select table name $table_name = "country"; //Build contents query $this->db->select('id,iso,name,printable_name,iso3,numcode')->from($table_name); $this->CI->flexigrid->build_query(); //Get contents $return['records'] = $this->db->get(); //echo $this->db->last_query(); //Build count query $this->db->select('count(id) as record_count')->from($table_name); $this->CI->flexigrid->build_query(FALSE); $record_count = $this->db->get(); $row = $record_count->row(); //Get Record Count $return['record_count'] = $row->record_count; //Return all return $return; } /** * Remove country * #param int country id * #return boolean */ public function delete_country($country_id) { $delete_country = $this->db->query('DELETE FROM country WHERE id='.$country_id); return TRUE; } } ?> My database is called country and database table is called also country. This is information in CI_Folder\system\application\config $db['default']['hostname'] = "localhost"; $db['default']['username'] = "root"; $db['default']['password'] = ""; $db['default']['database'] = "country"; $db['default']['dbdriver'] = "mysql"; Can you help me to write correct code inside flexigrid.php? This is my code for CI_Folder\system\application\helpers\flexigrid_helper.php but is correct? <?php if (!defined('BASEPATH')) exit('No direct script access allowed'); /** * Flexigrid CodeIgniter implementation * * PHP version 5 * * #category CodeIgniter * #package Flexigrid CI * #author Frederico Carvalho (frederico#eyeviewdesign.com) * #version 0.3 * Copyright (c) 2008 Frederico Carvalho (http://flexigrid.eyeviewdesign.com) * Dual licensed under the MIT (MIT-LICENSE.txt) * and GPL (GPL-LICENSE.txt) licenses. */ if (! function_exists('build_grid_js')) { /** * Build Javascript to display grid * * #param grid id, or the div id * #param url to make the ajax call * #param array with colModel info: * * 0 - display name * * 1 - width * * 2 - sortable * * 3 - align * * 4 - searchable (2 -> yes and default, 1 -> yes, 0 -> no.) * * 5 - hidden (TRUE or FALSE, default is FALSE. This index is optional.) * #param array with button info: * * 0 - display name * * 1 - bclass * * 2 - onpress * #param default sort column name * #param default sort order * #param array with aditional parameters * #return string */ function build_grid_js($grid_id,$url,$colModel,$sortname,$sortorder,$gridParams = NULL,$buttons = NULL) { //Basic propreties $grid_js = '<script type="text/javascript">$(document).ready(function(){'; $grid_js .= '$("#'.$grid_id.'").flexigrid({'; $grid_js .= "url: '".$url."',"; $grid_js .= "dataType: 'json',"; $grid_js .= "sortname: '".$sortname."',"; $grid_js .= "sortorder: '".$sortorder."',"; $grid_js .= "usepager: true,"; $grid_js .= "useRp: true,"; //Other propreties if (is_array($gridParams)) { //String exceptions that dont have ' '. Must be lower case. $string_exceptions = array("rpoptions"); //Print propreties foreach ($gridParams as $index => $value) { //Check and print with or without ' ' if (is_numeric($value)) { $grid_js .= $index.": ".$value.","; } else { if (is_bool($value)) if ($value == true) $grid_js .= $index.": true,"; else $grid_js .= $index.": false,"; else if (in_array(strtolower($index),$string_exceptions)) $grid_js .= $index.": ".$value.","; else $grid_js .= $index.": '".$value."',"; } } } $grid_js .= "colModel : ["; //Get colModel foreach ($colModel as $index => $value) { $grid_js .= "{display: '".$value[0]."', ".($value[2] ? "name : '".$index."', sortable: true," : "")." width : ".$value[1].", align: '".$value[3]."'".(isset($value[5]) && $value[5] ? ", hide : true" : "")."},"; //If item is searchable if ($value[4] != 0) { //Start searchitems var if (!isset($searchitems)) $searchitems = "searchitems : ["; $options = ''; if (isset($value['options'])) { if (isset($value['options']['type'])) { $options = ", type : '".$value['options']['type']."'"; switch($value['options']['type']) { case 'select' : $options .= ", editoptions : { value : '" . $value['options']['edit_options'] . "' }"; break; case 'date' : case 'radio' : case 'checkbox' : default : } } } if ($value[4] == 2) $searchitems .= "{display: '".$value[0]."', name : '".$index."', isdefault: true " .$options. "},"; else if ($value[4] == 1) $searchitems .= "{display: '".$value[0]."', name : '".$index."' " .$options. "},"; } } //Remove the last "," $grid_js = substr($grid_js,0,-1).'],'; $searchitems = substr($searchitems,0,-1).']'; //Add searchitems to grid $grid_js .= $searchitems; //Get buttons if (is_array($buttons)) { $grid_js .= ",buttons : ["; foreach ($buttons as $index => $value) { if ($value[0] == 'separator') $grid_js .= "{separator: true},"; else $grid_js .= "{name: '".$value[0]."', bclass : '".$value[1]."', onpress : ".$value[2]."},"; } //Remove the last "," $grid_js = substr($grid_js,0,-1).']'; } //Finalize $grid_js .= "}); })</script>"; return $grid_js; } } ?>
I solve looking here: https://github.com/sameersemna/ci-flexigrid Just download codeigniter-flexigrid project, import database and set database credentials in database.php. This is the live example from github project: http://ci-flexigrid.sameershemna.com/countries I like this solution because you do not need grocery-crud library but just simply codeigniter cheers
Google speech API - php does not return anything
My code is inspired by this php version of full duplex google speech API for speech-to-text : http://mikepultz.com/2013/07/google-speech-api-full-duplex-php-version/ I have few flac files that do work and give the array output as explained on Mike's post. But for few flac files it just doesn't return anything as output. For example : http://gavyadhar.com/video/upload/Pantry_Survey.flac, no output is returned. But the same code works for this flac file: http://gavyadhar.com/video/upload/pantry_snack_video.flac and returns the array output as following: ---------response 1 : your face a pantry and one of the main stacks I usually Wesley Rd rasa multigrain crackers and I like them because they're pretty healthy for you and [...] ...and so on 5 responses. Can anyone tell me, why is it that some flac files don't work? Or is there any way to catch the exceptions which are created by google API and display them to troubleshoot? Thanks. Attaching my code here of two php files: PHP file which passes the API key and the FLAC file with its sample rate. <?php include 'GoogleSpeechToText.php'; ini_set('display_errors',1); ini_set('display_startup_errors',1); error_reporting(-1); // Your API Key goes here. $apiKey = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXX'; // my API server key $speech = new GoogleSpeechToText($apiKey); #var_dump($speech); $file = realpath('upload/Pantry_Survey.flac'); // Full path to the file. echo "<BR><BR>file : ", $file ; #print_r("<br>-------------------"); #print_r($file1); #print_r("<br>-------------------"); $bitRate = 44100; // The bit rate of the file. $result = $speech->process($file, $bitRate, 'en-US'); print_r($result); echo "<BR><BR>-------------"; $responses = $result[0]['alternative']; $i = 0; foreach ($responses as $response) { $i = $i + 1; #echo $response['transcript']; echo "<br><br> ---------response $i : ", $response['transcript']; } ?> GoogleSpeechToText.php <?php /** * Convert FLAC files to Text using the Google Speech API * * Credit due to Mike (mike#mikepultz.com) for his first version of this. * * #version 0.1 * #author Roger Thomas * #see * */ class GoogleSpeechToText { /** * URL of the Speech API * #var string */ const SPEECH_BASE_URL = 'https://www.google.com/speech-api/full-duplex/v1/'; /** * A 'unique' string to use for the requests * * #var string */ private $requestPair; /** * The Google Auth API Key * * #var string */ private $apiKey; /** * CURL Upload Handle * * #var resource */ private $uploadHandle; /** * CURL Download Handle * * #var resource */ private $downloadHandle; /** * Construct giving the Google Auth API Key. * * #param string $apiKey * #throws Exception */ public function __construct($apiKey) { if (empty($apiKey)) { throw new Exception('$apiKey should not be empty.'); } $this->apiKey = $apiKey; $this->requestPair = $this->getPair(); $this->setupCurl(); } /** * Setup CURL requests, both up and down. */ private function setupCurl() { $this->uploadHandle = curl_init(); $this->downloadHandle = curl_init(); curl_setopt($this->downloadHandle, CURLOPT_URL, self::SPEECH_BASE_URL . 'down?pair=' . $this->requestPair ); #echo "<br>downloadHandle :: ", self::SPEECH_BASE_URL . 'down?pair=' . $this->requestPair; curl_setopt($this->downloadHandle, CURLOPT_RETURNTRANSFER, true); curl_setopt($this->uploadHandle,CURLOPT_RETURNTRANSFER,true); curl_setopt($this->uploadHandle,CURLOPT_POST,true); //----added by asmi shah - 7 jan 2015 curl_setopt($this->uploadHandle, CURLOPT_MAX_SEND_SPEED_LARGE, 30000); curl_setopt($this->uploadHandle, CURLOPT_LOW_SPEED_TIME, 9999); curl_setopt($this->downloadHandle, CURLOPT_LOW_SPEED_TIME, 9999); //---- } /** * Generate a Pair for the request. This identifies the requests later. * * #return string */ private function getPair() { $c = '0123456789'; $s = ''; for ($i=0; $i<16; $i++) { $s .= $c[rand(0, strlen($c) - 1)]; } echo "pair : ",$s; return $s; } /** * Make the request, returning either an array, or boolean false on * failure. * * #param string $file the file name to process * #param integer $rate the bitrate of the flac content (example: 44100) * #param string $language the ISO language code * (en-US has been confirmed as working) * #throws Exception * #return array|boolean false for failure. */ public function process($file, $rate, $language = 'en-US') { if (!$file || !file_exists($file) || !is_readable($file)) { throw new Exception( '$file must be specified and be a valid location.' ); } else { echo "<br>file exists"; } $data = file_get_contents($file); #var_dump($rate); if (!$data) { throw new Exception('Unable to read ' . $file); } else { echo "<br>file is readable"; } $upload_data = array( "Content_Type" => "audio/x-flac; rate=". $rate, "Content" => $data, ); if (empty($rate) || !is_integer($rate)) { throw new Exception('$rate must be specified and be an integer'); } else { echo "<br>sample rate is received :" . $rate ; } curl_setopt($this->uploadHandle,CURLOPT_URL,self::SPEECH_BASE_URL . 'up?lang=' .$language . '&lm=dictation&timeout=20&client=chromium&pair=' .$this->requestPair . '&key=' . $this->apiKey); curl_setopt($this->uploadHandle,CURLOPT_HTTPHEADER,array('Transfer-Encoding: chunked','Content-Type: audio/x-flac; rate=' . $rate)); curl_setopt($this->uploadHandle,CURLOPT_POSTFIELDS,$upload_data); #echo "<br><br>------ data : ", $data; #echo "<br><br>------"; #echo "<BR><BR> URL made up : ", self::SPEECH_BASE_URL . 'up?lang=' .$language . '&lm=dictation&client=chromium&pair=' .$this->requestPair . '&key=' . $this->apiKey; $curlMulti = curl_multi_init(); curl_multi_add_handle($curlMulti, $this->downloadHandle); curl_multi_add_handle($curlMulti, $this->uploadHandle); $active = null; do { curl_multi_exec($curlMulti, $active); } while ($active > 0); $res = curl_multi_getcontent($this->downloadHandle); #var_dump($this->downloadHandle); #echo "resource type ::".get_resource_type($this->downloadHandle); $output = array(); $results = explode("\n", $res); #var_dump($results); #$i = 0; foreach ($results as $result) { #$i = $i + 1; #echo "<BR><BR><BR>--------------- string ||$i|| : ", $result; $object = json_decode($result, true); if ( (isset($object['result']) == true) && (count($object['result']) > 0) ) { foreach ($object['result'] as $obj) { $output[] = $obj; } } } curl_multi_remove_handle($curlMulti, $this->downloadHandle); curl_multi_remove_handle($curlMulti, $this->uploadHandle); curl_multi_close($curlMulti); if (empty($output)) { echo "<BR><br>output is empty<BR>"; return false; } echo "<BR><BR>"; return $output; } /** * Close any outstanding connections in the destruct */ public function __destruct() { curl_close($this->uploadHandle); curl_close($this->downloadHandle); } } ?>
The audio file you provided uses 2 channels. As speech currently only supports single channel audio, you will need to convert it down to a single channel. All encodings support only 1 channel (mono) audio. Audio encoding detail of Google speech API After converting the audio file down to 1 channel I was able to successfully get a response with the provided audio file.
For your information the SPEECH_BASE_URL = 'https://www.google.com/speech-api/full-duplex/v1/'; is now deprecated, the new one is: https://speech.googleapis.com/v1/speech:recognize?key=YOUR_API_KEY as per https://cloud.google.com/speech/docs/auth#using_an_api_key
joomla 1.7 : overriding pagination.php not working
I installed joomla 1.7(window/xampp/php 5.3) and my current template is beez_20. I have to override the pagination.php and to do so I copied the pagination.php from \libraries\joomla\html to \templates\beez_20\html. When I reload the home page, I am getting a broken template as in the following picture. I get the normal page when I remove the pagination.php from the html folder. I believe this is the correct method to override the pagination.php what is missing ? need to change any configuration ? please post your comments Thanks in advance
I do belive this is the correct way to do it... Here is a pagnation.php for you to try with (works for me): <?php // no direct access defined('_JEXEC') or die('Restricted access'); /** * This is a file to add template specific chrome to pagination rendering. * * pagination_list_footer * Input variable $list is an array with offsets: * $list[limit] : int * $list[limitstart] : int * $list[total] : int * $list[limitfield] : string * $list[pagescounter] : string * $list[pageslinks] : string * * pagination_list_render * Input variable $list is an array with offsets: * $list[all] * [data] : string * [active] : boolean * $list[start] * [data] : string * [active] : boolean * $list[previous] * [data] : string * [active] : boolean * $list[next] * [data] : string * [active] : boolean * $list[end] * [data] : string * [active] : boolean * $list[pages] * [{PAGE}][data] : string * [{PAGE}][active] : boolean * * pagination_item_active * Input variable $item is an object with fields: * $item->base : integer * $item->link : string * $item->text : string * * pagination_item_inactive * Input variable $item is an object with fields: * $item->base : integer * $item->link : string * $item->text : string * * This gives template designers ultimate control over how pagination is rendered. * * NOTE: If you override pagination_item_active OR pagination_item_inactive you MUST override them both */ function pagination_list_footer($list) { // Initialize variables $lang =& JFactory::getLanguage(); $html = "<div class=\"list-footer\">\n"; if ($lang->isRTL()) { $html .= "\n<div class=\"counter\">".$list['pagescounter']."</div>"; $html .= $list['pageslinks']; $html .= "\n<div class=\"limit\">".JText::_('Display Num').$list['limitfield']."</div>"; } else { $html .= "\n<div class=\"limit\">".JText::_('Display Num').$list['limitfield']."</div>"; $html .= $list['pageslinks']; $html .= "\n<div class=\"counter\">".$list['pagescounter']."</div>"; } $html .= "\n<input type=\"hidden\" name=\"limitstart\" value=\"".$list['limitstart']."\" />"; $html .= "\n</div>"; return $html; } function pagination_list_render($list) { // Initialize variables $lang =& JFactory::getLanguage(); $html = "<div class=\"pagination\"><ul>"; // Reverse output rendering for right-to-left display if($lang->isRTL()) { $html .= "<li class=\"pagination-start\">".$list['start']['data']."</li>"; $html .= "<li class=\"pagination-prev\">".$list['previous']['data']."</li>"; $list['pages'] = array_reverse( $list['pages'] ); foreach( $list['pages'] as $page ) { if($page['data']['active']) { // $html .= '<strong>'; } $html .= "<li>".$page['data']."</li>"; if($page['data']['active']) { // $html .= '</strong>'; } } $html .= "<li class=\"pagination-next\">".$list['next']['data']."</li>"; $html .= "<li class=\"pagination-end\">".$list['end']['data']."</li>"; // $html .= '«'; } else { foreach( $list['pages'] as $page ) { if($page['data']['active']) { // $html .= '<strong>'; } $html .= "<li>".$page['data']."</li>"; if($page['data']['active']) { // $html .= '</strong>'; } } } $html .= "</ul></div>"; return $html; } ?>
You should not override the entire pagination.php in the manner you tried. You can only override certain functions. The reason you are seeing this page is because if you copied the entire pagination.php file with out changing anything, so you are re-declaring the JPagination class and you can't do that. When you are try to make changes to the pagination.php you should only re-write the functions you wish to override not copy the entire file. Please check out this article it's a little dated but the information still applies even in J! 2.5 http://docs.joomla.org/Understanding_Output_Overrides
Doctrine ODM / PHP / MongoDB - ReferenceOne ID changed or nulled when flushed
I'm trying to do a simple ReferenceOne with MongoDB/Doctrine, but I get a really weird problem: My ID:4e63611cbc347053a2000001 Create the Privilege Object Check what's the Privilege->User Id 4e63611cbc347053a2000001 Persist it Create the Event Object Persist it Check what's the Event->Privilege->User Id 4e63611cbc347053a2000001/OK/0 Flush it Get my document id 4e6546d6bc34700605000012 Check what's the Event->Privilege->User Id 4e6546d6bc34700605000013/NOK/0 As you can see here, I create a Privilege Object where I reference a User, I persist it => all ok. No I create a Event Object, I embed the Privilege in it, check the id => all ok. Now I flush it, and the user->id gets changed, I have no idea why this happens. I tried removing the cascade to see how it behaves and I just end up with a null $id. Any help would be welcome to understand what I'm doing wrong! Here is the code I use: echo "My ID:".$identity->getId()."<br />"; echo "Create the Privilege Object<br />"; $privilege = new \Entity\ODM\Event\Privilege(); $privilege->setUser($identity); $privilege->setRole("admin"); echo "Check what's the Privilege->User Id<br />"; echo $privilege->getUser()->getId()."<br />"; echo "Persist it<br />"; $dm->persist($privilege); echo "Create the Event Object<br />"; $event = new \Entity\ODM\Event(); $event->setName("My Event 222"); $event->setDate("25/08/2012"); $event->setUrl("myevent222"); $event->addPrivilege($privilege); echo "Persist it<br />"; $dm->persist($event); echo "Check what's the Event->Privilege->User Id<br />"; $privs = $event->getPrivileges(); $output = $identity->getId(); $i = 0; foreach($privs as $priv) { if($priv->getUser()->getId() == '4e63611cbc347053a2000001') $output .= "/OK/".$i."<br />"; else $output .= "/NOK/".$i."<br />"; $i++; echo $output; } echo "Flush it<br />"; $dm->flush(); echo "Get my document id<br/>"; $id = $event->getId(); echo $id."<br/>"; $privs = null; $priv = null; echo "Check what's the Event->Privilege->User Id<br />"; $privs = $event->getPrivileges(); $output = $identity->getId(); $i = 0; foreach($privs as $priv) { if($priv->getUser()->getId() == '4e63611cbc347053a2000001') $output .= "/OK/".$i."<br />"; else $output .= "/NOK/".$i."<br />"; $i++; echo $output; } Trimmed Entities: class Event { /** * #Id */ protected $id; /** * #EmbedMany(targetDocument="\Entity\ODM\Event\Privilege") */ protected $privileges = array(); } class Privilege { /** * #Id */ protected $id; /** * #ReferenceOne(targetDocument="\Entity\ODM\User", cascade={"persist"}) */ protected $user; /** * #param field_type $user */ public function setUser(\Entity\ODM\User $user) { $this->user = $user; } }
For some reason the code here works perfectly fine under symfony2. The problem is coming from the way I implemented doctrine in Zend (modified Bisna) - Closing this question.