Generate entities with prefix in Doctrine2 - doctrine

I'm using doctrine2 with Zend Framework. When you build the entites need to set the prefix of the classes, for example (Model_User). Is it possible?. The command I use is
./doctrine orm:generate-entities --generate-annotations=1 ../../../application/models/

I'm new to Doctrine orm but I made this:
class TablePrefix{
protected $prefix = '';
public function __construct($prefix){
$this->prefix = '';
for($i = 0; $i < strlen($prefix); $i++){ // table prefix like in entity name
if( $prefix[$i] == '_' && $i-1 > 0 ){
$prefix[$i-1] = strtoupper($prefix[$i-1]);
}
else{
$this->prefix .= $prefix[$i];
}
}
$this->prefix[0] = strtoupper($this->prefix[0]);
}
public function loadClassMetadata(LoadClassMetadataEventArgs $eventArgs){
$classMetadata = $eventArgs->getClassMetadata();
$tmp = substr($classMetadata->name, 0, strlen($this->prefix));
if($tmp == $this->prefix ){
$classMetadata->name = substr($classMetadata->name, strlen($this->prefix));
}
}
}
next when you create entity manager make this:
$tablePrefix = new TablePrefix('tbl_');
$evm = $entityManager->getEventManager();
$evm->addEventListener(\Doctrine\ORM\Events::loadClassMetadata, $tablePrefix);
on top of file add:use \Doctrine\ORM\Event\LoadClassMetadataEventArgs;
when you run cmd php vendor/bin/doctrine orm:generate-entities models model's name will be ok!

add these lines in your application.ini file.
doctrine.generate_models_options.pearStyle = true
doctrine.generate_models_options.generateTableClasses = false
doctrine.generate_models_options.generateBaseClasses = true
doctrine.generate_models_options.baseClassPrefix = "Base_"
doctrine.generate_models_options.baseClassesDirectory =
doctrine.generate_models_options.classPrefixFiles = false
doctrine.generate_models_options.classPrefix = "ModuleName_Model_"

Related

doctrine query with parameters having multiple values

I want to make a doctrine query in which each parameters can have multiple values (coming from a select multiple).
I have a table with a 'type' parameter that can have value of 1, 2, 3 or 4 and an 'online' parameter that can be 0 or 1.
My query so far is the following :
$query = $this->createQueryBuilder('properties');
if (array_key_exists('type', $searchValues)) {
$types = $searchValues['type'];
$iterator = 0;
foreach ($types as $type) {
if ($iterator == 0) {
$query->andWhere('properties.idPropertyType = ' . $type);
} else {
$query->orWhere('properties.onlineProperties = ' . $type);
}
$iterator++;
}
}
if (array_key_exists('status', $searchValues)) {
$status = $searchValues['status'];
$iterator = 0;
foreach ($status as $statu) {
if ($iterator == 0) {
$query->andwhere('properties.onlineProperties = ' . $statu);
} else {
$query->andWhere('properties.onlineProperties = ' . $statu);
}
$iterator++;
}
}
$properties = $query->getQuery()->getResult();
In the case of a search with parameter type = 1 and online = 0 and 1, I have results where type is another value than 1. I understand the reason why but I cannot figure out a proper way to make my query.
You don't need to build your query by hand manually, just use the (in) function from the QueryBuilder class. Try this:
$query = $this->createQueryBuilder('properties');
if(array_key_exists('type', $searchValues)){
$types = $searchValues['type'];
$query->andWhere($query->expr()->in('properties.idPropertyType', $types));
}
if(array_key_exists('status', $searchValues)){
$status = $searchValues['status'];
$query->andwhere($query->expr()->in('properties.onlineProperties', $status));
}
$properties = $query->getQuery()->getResult();

Phalcon use Oracle views

In a Phalcon project, I have multiple database in Oracle and mySQL with number of tables and views. Created models for corresponding tables and views. But unable to access views. I initialize in model below:
public function initialize()
{
$this->setConnectionService('dbBznes');
$this->setSchema('POLICY');
$this->setSource("BUSINESS_ALL");
}
As per the comments, this is apparently a metadata issue and the default metadata strategy is introspection and is attempting to check if the table exists. You can set up your own metadata strategy like so:
$di['modelsMetadata'] = function()
{
$metadata = new \Phalcon\Mvc\Model\MetaData\Memory();
$metadata->setStrategy(
new MyIntrospectionStrategy()
);
return $metadata;
};
"Memory" in this case means don't use any sort of metadata caching. This goes off into another tangent as you can cache in many ways for more speed in production, etc.
As for the MyIntrospectionStrategy class above, it represents your own class based on Phalcon's Introspection strategy which attempts to analyze the database to figure out the fields and their types involved with the table.
I believe I converted Phalcon\Mvc\Model\MetaData\Strategy\Introspection from Zephir to PHP correctly as follows:
class MyIntrospectionStrategy implements \Phalcon\Mvc\Model\MetaData\StrategyInterface
{
public final function getMetaData(\Phalcon\Mvc\ModelInterface $model, \Phalcon\DiInterface $dependencyInjector)
{
$schema = $model->getSchema();
$table = $model->getSource();
$readConnection = $model->getReadConnection();
if( !$readConnection->tableExists($table, $schema) )
{
if($schema)
{
$completeTable = $schema . "'.'" . $table;
} else {
$completeTable = $table;
}
throw new \Phalcon\Mvc\Model\Exception(
"Table '" . $completeTable . "' doesn't exist in database when dumping meta-data for " . get_class($model)
);
}
$columns = $readConnection->describeColumns($table, $schema);
if( !count($columns) )
{
if($schema)
{
$completeTable = $schema . "'.'" . $table;
} else {
$completeTable = $table;
}
/**
* The table not exists
*/
throw new \Phalcon\Mvc\Model\Exception(
"Cannot obtain table columns for the mapped source '" . completeTable . "' used in model " . get_class(model)
);
}
$attributes = [];
$primaryKeys = [];
$nonPrimaryKeys = [];
$numericTyped = [];
$notNull = [];
$fieldTypes = [];
$fieldBindTypes = [];
$automaticDefault = [];
$identityField = false;
$defaultValues = [];
$emptyStringValues = [];
foreach($columns as $column)
{
$fieldName = $column->getName();
$attributes[] = $fieldName;
if ($column->isPrimary() === true)
{
$primaryKeys[] = $fieldName;
} else {
$nonPrimaryKeys[] = $fieldName;
}
if ($column->isNumeric() === true)
{
$numericTyped[$fieldName] = true;
}
if ($column->isNotNull() === true)
{
$notNull[] = $fieldName;
}
if ($column->isAutoIncrement() === true)
{
$identityField = $fieldName;
}
$fieldTypes[$fieldName] = $column->getType();
$fieldBindTypes[$fieldName] = $column->getBindType();
$defaultValue = $column->getDefault();
if ($defaultValue !== null || $column->isNotNull() === false)
{
if ( !$column->isAutoIncrement() )
{
$defaultValues[$fieldName] = $defaultValue;
}
}
}
return [
\Phalcon\Mvc\Model\MetaData::MODELS_ATTRIBUTES => $attributes,
\Phalcon\Mvc\Model\MetaData::MODELS_PRIMARY_KEY => $primaryKeys,
\Phalcon\Mvc\Model\MetaData::MODELS_NON_PRIMARY_KEY => $nonPrimaryKeys,
\Phalcon\Mvc\Model\MetaData::MODELS_NOT_NULL => $notNull,
\Phalcon\Mvc\Model\MetaData::MODELS_DATA_TYPES => $fieldTypes,
\Phalcon\Mvc\Model\MetaData::MODELS_DATA_TYPES_NUMERIC => $numericTyped,
\Phalcon\Mvc\Model\MetaData::MODELS_IDENTITY_COLUMN => $identityField,
\Phalcon\Mvc\Model\MetaData::MODELS_DATA_TYPES_BIND => $fieldBindTypes,
\Phalcon\Mvc\Model\MetaData::MODELS_AUTOMATIC_DEFAULT_INSERT => $automaticDefault,
\Phalcon\Mvc\Model\MetaData::MODELS_AUTOMATIC_DEFAULT_UPDATE => $automaticDefault,
\Phalcon\Mvc\Model\MetaData::MODELS_DEFAULT_VALUES => $defaultValues,
\Phalcon\Mvc\Model\MetaData::MODELS_EMPTY_STRING_VALUES => $emptyStringValues
];
}
public final function getColumnMaps(\Phalcon\Mvc\ModelInterface $model, \Phalcon\DiInterface $dependencyInjector)
{
$orderedColumnMap = null;
$reversedColumnMap = null;
if (method_exists($model, 'columnMap'))
{
$userColumnMap = $model->columnMap();
if ( gettype($userColumnMap) != 'array')
{
// Bad grammer directly in cphalcon :sadface:
throw new \Phalcon\Mvc\Model\Exception('columnMap() not returned an array');
}
$reversedColumnMap = [];
$orderedColumnMap = $userColumnMap;
foreach($userColumnMap as $name => $userName)
{
$reversedColumnMap[$userName] = $name;
}
}
return [$orderedColumnMap, $reversedColumnMap];
}
}
I have not tested this.
As far as adding support for views to be treated like tables, the change might be as simple as:
Before:
if( !$readConnection->tableExists($table, $schema) )
After:
if( !$readConnection->tableExists($table, $schema) && !$readConnection->viewExists($table, $schema) )
If this doesn't work due to logic choking with describeColumns, you might need to write something specific for working with views in Oracle for this dialect.
As far as other solutions, you can provide your own metadata method directly on the model by specifying your ownmetaData method directly on it.
Another solution is to use annotations instead of introspection for metadata.
Then you'd place your metadata as comments in the code for Phalcon to parse.
If you continue to run into problems with Database Views, just run it as raw SQL rather than attempting to use the ORM to do it. You can simply define a new method on your model to run the raw SQL.

Laravel 5.3 database transaction issue?

I have used more time with Laravel 5.0 on database transaction but when I change to Laravel 5.3.* it not work as I want even I have disabled commit() method all data still continue insert into database.
if ($request->isMethod('post')) {
DB::beginTransaction();
$cats = new Cat();
$cats->parent_id = $this->request->input('category_id');
$cats->status = ($this->request->input('status')) ? $this->request->input('status') : 0;
if ($res['cat'] = $cats->save()) {
$catD = new CategoryDescriptions();
$catD->category_id = $cats->id;
$catD->language_id = 1;
$catD->name = $this->request->input('en_name');
if ($res['cat2'] = $catD->save()) {
$catD2 = new CategoryDescriptions();
$catD2->category_id = $cats->id;
$catD2->language_id = 2;
$catD2->name = $this->request->input('kh_name');
$res['all'] = $catD2->save();
}
}
if ($res) {
//DB::commit();
return $res;
}
return [false];
}
Check this line ($res['cat'] is a boolean):
if($res['cat'] = $cats->save()) {
And this ($res is an array. You compare an array as boolean!):
if($res){
The right condition should be:
$res = array(); // the first line of your method
// .... your http method check, start transaction, etc.
if (!in_array(false, $res, true)) { // check if array doesn't contain 'false values'
DB::commit();
}

access folder outside CodeIgniter

I've been to trying to upload images using code igniter and it works perfectly when the upload folder is just outside of application folder. But my problem is when I try to access folder which is outside whole code igniter folder it is throwing me a error. How to access the folder outside the code igniter folder? I tried $_SERVER['DOCUMENT_ROOT']. But it dint help.
$name = $_POST['name'];
$id = $_POST['id'];
if (isset($_FILES['upload']['name'])) {
// total files //
$count = count($_FILES['upload']['name']);
// all uploads //
$uploads = $_FILES['upload'];
for ($i = 0; $i < $count; $i++) {
if ($uploads['error'][$i] == 0) {
$firstimage = $uploads['name'][$i];
$secondimage = $uploads['name'][$i];
move_uploaded_file($uploads['tmp_name'][$i], $_SERVER['DOCUMENT_ROOT'].'tuition/tuitionimage/'.$id.'/'.$uploads['name'][$i]);
$config2['image_library'] = 'gd2';
$config2['source_image'] = $_SERVER['DOCUMENT_ROOT'].'tuition/tuitionimage/'.$id.'/'.$uploads['name'][$i];
$config2['new_image'] = $_SERVER['DOCUMENT_ROOT'].'tuition/tuitionimage/'.$id.'/thumbnail/'.$uploads['name'][$i];
$config2['maintain_ratio'] = FALSE;
$config2['create_thumb'] = TRUE;
$config2['thumb_marker'] = '_thumb';
$config2['width'] = 75;
$config2['height'] = 50;
$config2['overwrite'] = TRUE;
$this->image_lib->initialize($config2);
$this->load->library('image_lib',$config2);
if ( ! $this->image_lib->resize())
{
echo $this->image_lib->display_errors();
}
$config3['image_library'] = 'gd2';
$config3['source_image'] = $_SERVER['DOCUMENT_ROOT'].'tuition/tuitionimage/'.$id.'/'.$uploads['name'][$i];
$config3['new_image'] = $_SERVER['DOCUMENT_ROOT'].'tuition/tuitionimage/'.$id.'/resize/'.$uploads['name'][$i];
$config3['maintain_ratio'] = FALSE;
$config3['create_thumb'] = TRUE;
$config3['thumb_marker'] = '_thumb';
$config3['width'] = 470;
$config3['height'] = 470;
$config3['overwrite'] = TRUE;
$this->image_lib->initialize($config3);
$this->load->library('image_lib',$config3);
if ( ! $this->image_lib->resize())
{
echo $this->image_lib->display_errors();
}
}
}
$this->load->view('head');
$data = array(
'name' => $name,
'id' => $id
);
After discussing in comments, the problem is likely the move_uploaded_file() function is trying to move the file to a directory that doesn't exist yet.
move_uploaded_file($uploads['tmp_name'][$i], $_SERVER['DOCUMENT_ROOT'].'tuition/tuitionimage/'.$id.'/'.$uploads['name'][$i]);
Before the file can be moved the folder needs to be created. If $id is new, it has probably not been created yet. So...
if (!is_dir($_SERVER['DOCUMENT_ROOT'].'tuition/tuitionimage/'.$id)) {
mkdir($_SERVER['DOCUMENT_ROOT'].'tuition/tuitionimage/'.$id);
}
move_uploaded_file($uploads['tmp_name'][$i], $_SERVER['DOCUMENT_ROOT'].'tuition/tuitionimage/'.$id.'/'.$uploads['name'][$i]);

Add "latest items by category" block in item view page of K2 component

I am using Joomla! K2 v2.4.1 component on Joomla! v1.5.23. I want to display latest items by category in the item view page, the category being the current one which the current viewed item belongs to.
There are modules which I can use to display most recent items by category but I want to modify item.php and other related files (actually I don't know which files to edit except the item.php template file) to accommodate this requirement. Is it possible to achieve this? If yes, which files do I need to edit and with what code?
Given below is what I think is used to retrieve latest items by category.
class K2ViewLatest extends JView {
function display($tpl = null) {
$mainframe = &JFactory::getApplication();
$params = &JComponentHelper::getParams('com_k2');
$user = &JFactory::getUser();
$cache = &JFactory::getCache('com_k2_extended');
$limit = $params->get('latestItemsLimit',3);
$limitstart = JRequest::getInt('limitstart');
$model = &$this->getModel('itemlist');
$itemModel = &$this->getModel('item');
if($params->get('source')){
$categoryIDs = $params->get('categoryIDs');
if(is_string($categoryIDs) && !empty($categoryIDs)){
$categoryIDs = array();
$categoryIDs[]=$params->get('categoryIDs');
}
$categories = array();
JTable::addIncludePath(JPATH_ADMINISTRATOR.DS.'components'.DS.'com_k2'.DS.'tables');
if(is_array($categoryIDs)){
foreach($categoryIDs as $categoryID){
$category = & JTable::getInstance('K2Category', 'Table');
$category->load($categoryID);
if ($category->published && ($category->access <= $user->get('aid', 0))) {
//Merge params
$cparams = new JParameter($category->params);
if ($cparams->get('inheritFrom')) {
$masterCategory = &JTable::getInstance('K2Category', 'Table');
$masterCategory->load($cparams->get('inheritFrom'));
$cparams = new JParameter($masterCategory->params);
}
$params->merge($cparams);
//Category image
if (! empty($category->image)) {
$category->image = JURI::root().'media/k2/categories/'.$category->image;
} else {
if ($params->get('catImageDefault')) {
$category->image = JURI::root().'components/com_k2/images/placeholder/category.png';
}
}
//Category plugins
$dispatcher = &JDispatcher::getInstance();
JPluginHelper::importPlugin('content');
$category->text = $category->description;
$dispatcher->trigger('onPrepareContent', array ( & $category, &$params, $limitstart));
$category->description = $category->text;
//Category K2 plugins
$category->event->K2CategoryDisplay = '';
JPluginHelper::importPlugin('k2');
$results = $dispatcher->trigger('onK2CategoryDisplay', array(&$category, &$params, $limitstart));
$category->event->K2CategoryDisplay = trim(implode("\n", $results));
$category->text = $category->description;
$dispatcher->trigger('onK2PrepareContent', array ( & $category, &$params, $limitstart));
$category->description = $category->text;
//Category link
$link = urldecode(K2HelperRoute::getCategoryRoute($category->id.':'.urlencode($category->alias)));
$category->link = JRoute::_($link);
$category->feed = JRoute::_($link.'&format=feed');
JRequest::setVar('view', 'itemlist');
JRequest::setVar('task', 'category');
JRequest::setVar('id', $category->id);
JRequest::setVar('featured', 1);
JRequest::setVar('limit', $limit);
JRequest::setVar('clearFlag', true);
$category->name = htmlspecialchars($category->name, ENT_QUOTES);
$category->items = $model->getData('rdate');
JRequest::setVar('view', 'latest');
JRequest::setVar('task', '');
for ($i = 0; $i < sizeof($category->items); $i++) {
if ($user->guest){
$hits = $category->items[$i]->hits;
$category->items[$i]->hits = 0;
$category->items[$i] = $cache->call(array('K2ModelItem', 'prepareItem'), $category->items[$i], 'latest', '');
$category->items[$i]->hits = $hits;
}
else {
$category->items[$i] = $itemModel->prepareItem($category->items[$i], 'latest', '');
}
$category->items[$i] = $itemModel->execPlugins($category->items[$i], 'latest', '');
//Trigger comments counter event
$dispatcher = &JDispatcher::getInstance();
JPluginHelper::importPlugin ('k2');
$results = $dispatcher->trigger('onK2CommentsCounter', array ( & $category->items[$i], &$params, $limitstart));
$category->items[$i]->event->K2CommentsCounter = trim(implode("\n", $results));
}
$categories[]=$category;
}
}
}
$source = 'categories';
$this->assignRef('blocks', $categories);
} else {
$usersIDs = $params->get('userIDs');
if(is_string($usersIDs) && !empty($usersIDs)){
$usersIDs = array();
$usersIDs[]=$params->get('userIDs');
}
$users = array();
if(is_array($usersIDs)){
foreach($usersIDs as $userID){
$userObject = JFactory::getUser($userID);
if (!$userObject->block) {
//User profile
$userObject->profile = $model->getUserProfile($userID);
//User image
$userObject->avatar = K2HelperUtilities::getAvatar($userObject->id, $userObject->email, $params->get('userImageWidth'));
//User K2 plugins
$userObject->event->K2UserDisplay = '';
if (is_object($userObject->profile) && $userObject->profile->id > 0) {
$dispatcher = &JDispatcher::getInstance();
JPluginHelper::importPlugin('k2');
$results = $dispatcher->trigger('onK2UserDisplay', array(&$userObject->profile, &$params, $limitstart));
$userObject->event->K2UserDisplay = trim(implode("\n", $results));
}
$link = K2HelperRoute::getUserRoute($userObject->id);
$userObject->link = JRoute::_($link);
$userObject->feed = JRoute::_($link.'&format=feed');
$userObject->name = htmlspecialchars($userObject->name, ENT_QUOTES);
$userObject->items = $model->getAuthorLatest(0,$limit,$userID);
for ($i = 0; $i < sizeof($userObject->items); $i++) {
if ($user->guest){
$hits = $userObject->items[$i]->hits;
$userObject->items[$i]->hits = 0;
$userObject->items[$i] = $cache->call(array('K2ModelItem', 'prepareItem'), $userObject->items[$i], 'latest', '');
$userObject->items[$i]->hits = $hits;
}
else {
$userObject->items[$i] = $itemModel->prepareItem($userObject->items[$i], 'latest', '');
}
//Plugins
$userObject->items[$i] = $itemModel->execPlugins($userObject->items[$i], 'latest', '');
//Trigger comments counter event
$dispatcher = &JDispatcher::getInstance();
JPluginHelper::importPlugin ('k2');
$results = $dispatcher->trigger('onK2CommentsCounter', array ( & $userObject->items[$i], &$params, $limitstart));
$userObject->items[$i]->event->K2CommentsCounter = trim(implode("\n", $results));
}
$users[]=$userObject;
}
}
}
$source = 'users';
$this->assignRef('blocks', $users);
}
//Look for template files in component folders
$this->_addPath('template', JPATH_COMPONENT.DS.'templates');
$this->_addPath('template', JPATH_COMPONENT.DS.'templates'.DS.'default');
//Look for overrides in template folder (K2 template structure)
$this->_addPath('template', JPATH_SITE.DS.'templates'.DS.$mainframe->getTemplate().DS.'html'.DS.'com_k2'.DS.'templates');
$this->_addPath('template', JPATH_SITE.DS.'templates'.DS.$mainframe->getTemplate().DS.'html'.DS.'com_k2'.DS.'templates'.DS.'default');
//Look for overrides in template folder (Joomla! template structure)
$this->_addPath('template', JPATH_SITE.DS.'templates'.DS.$mainframe->getTemplate().DS.'html'.DS.'com_k2'.DS.'default');
$this->_addPath('template', JPATH_SITE.DS.'templates'.DS.$mainframe->getTemplate().DS.'html'.DS.'com_k2');
//Assign params
$this->assignRef('params', $params);
$this->assignRef('source', $source);
//Set layout
$this->setLayout('latest');
//Display
parent::display($tpl);
}
}
But this file is somehow used to retrieve items in using menu link. I am sorry if this is not the case.
In order to make this work the way you want you would have to modify the K2 item model. The data you want to display (recent items in category) is not currently being pulled from the database so you'd have to change to model to accommodate that. You would be much better off using the K2 content module to pull the most recent items instead. It wouldn't require hacking any core K2 code.
Also, you really need to update your software. K2 is on v2.5.4 and Joomla is on 2.5.1.

Resources