Get multiple custom taxonomy and terms index using json-api - wordpress

I use json-api plugin and I have three custom taxonomies. for example: car, phone, and book. I try to get all taxonomy index something like this
http://example.com/api/taxonomy/get_taxonomy_index/?taxonomy=car,phone,book
But it doesn't work for more than one taxonomy. Does Anyone know how to get all my custom taxonomy and terms index?
Here is JSON_API_Taxonomy_Controller:
class JSON_API_Taxonomy_Controller {
public function get_taxonomy_index() {
$terms = $this->get_terms();
return array(
'count' => count( $terms ),
'terms' => $terms
);
}
public function get_terms() {
global $json_api;
$taxonomy = $this->get_current_taxonomy();
if (!$taxonomy) {
$json_api->error("Not found.");
}
$wp_terms = get_terms( $taxonomy );
$terms = array();
foreach ( $wp_terms as $wp_term ) {
if ( $wp_term->term_id == 1 && $wp_term->slug == 'uncategorized' ) {
continue;
}
$terms[] = new JSON_API_Term( $wp_term );
}
return $terms;
}
protected function get_current_taxonomy() {
global $json_api;
$taxonomy = $json_api->query->get('taxonomy');
if ( $taxonomy ) {
return $taxonomy;
} else {
$json_api->error("Include 'taxonomy' var in your request.");
}
return null;
}
}
// Generic rewrite of JSON_API_Tag class to represent any term of any type of taxonomy in WP
class JSON_API_Term {
var $id; // Integer
var $slug; // String
var $title; // String
var $description; // String
function JSON_API_Term($term = null) {
if ($term) {
$this->import_wp_object($term);
}
}
function import_wp_object($term) {
$this->id = (int) $term->term_id;
$this->slug = $term->slug;
$this->title = $term->name;
$this->description = $term->description;
$this->post_count = (int) $term->count;
}
}
So I want json object output: registered taxonomies as parent and terms as child.

Related

Display Excerpts of Posts in Wordpress Blog

I have been searching for the answer to my problem and I continually come up with replacing
<?php the_content(); ?>
with
<?php the_excerpt(); ?>
in the index.php file. However, the theme we are using does not contain this line. Anyone have any insight? Here is the code in our index.php file:
<?php $t =& peTheme(); ?>
<?php $content =& $t->content; ?>
<?php $meta =& $content->meta(); ?>
<?php get_header(); ?>
<section class="section-blog section-index" id="<?php $content->slug(); ?>">
<div class="row">
<div class="large-12 columns text-center">
</div>
</div>
<div class="row blog-main">
<div class="large-9 columns blog-left">
<?php $t->content->loop(); ?>
</div>
<?php get_sidebar(); ?>
</div>
</section>
<?php get_footer(); ?>
Source of PeThemeContent.php:
<?php
class PeThemeContent {
protected $master;
protected $loops = array();
protected $current = false;
protected $blogLoop = false;
protected $cols = 0;
public function __construct(&$master) {
$this->master = &$master;
add_filter("pe_post_thumbnail",array(&$this,"post_thumbnail_filter"));
add_filter("wp_tag_cloud",array(&$this,"wp_tag_cloud_filter"));
add_filter("widget_tag_cloud_args",array(&$this,"widget_tag_cloud_args_filter"));
add_filter("previous_post_link",array(&$this,"strip_rel_filter"));
add_filter("next_post_link",array(&$this,"strip_rel_filter"));
add_filter("the_category",array(&$this,"strip_rel_filter"));
add_filter("excerpt_more",array(&$this,"excerpt_more_filter"));
add_filter("the_content_more_link",array(&$this,"the_content_more_link_filter"));
add_filter("edit_post_link",array(&$this,"edit_post_link_filter"));
}
public function instantiate() {
}
public function loop($name = "") {
$view = new PeThemeViewBlog;
$conf = (object) array("settings" => (object) array("layout" => $name));
$conf->settings->pager = "yes";
$conf->settings->media = "yes";
$view->output($conf);
}
public function have_posts() {
if ($this->current) {
//print_r($this->current);
$res = $this->current->have_posts();
} else {
$res = have_posts();
}
return $res;
}
public function idx() {
return $this->wpq->current_post;
}
public function last() {
return $this->wpq->post_count-1;
}
public function count() {
return $this->wpq->post_count;
}
public function is_single() {
return $this->current ? false : is_single();
}
public function the_post() {
if ($this->current) {
$res = $this->current->the_post();
$GLOBALS["more"] = false;
} else {
$res = the_post();
}
return $res;
}
public function beginRow($markup) {
$cols = $this->cols;
$idx = $this->wpq->current_post;
if ($cols > 0 && ($idx % $cols) == 0) {
echo $markup;
}
}
public function endRow($markup = "</div>") {
$cols = $this->cols;
$idx = $this->wpq->current_post;
$last = $this->wpq->post_count-1;
if ($cols > 0 && (($idx == $last) || ($idx % $cols) == ($cols-1))) {
echo $markup;
}
}
public function looping($cols = 0) {
if ($this->have_posts()) {
$this->cols = $cols;
$this->the_post();
return true;
}
return false;
}
public function &wpq() {
global $wp_query;
return $wp_query;
}
public function &__get($what) {
switch ($what) {
case "wpq":
if ($this->current) {
return $this->current;
}
return $this->wpq();
case "qv":
return $this->wpq()->query_vars;
case "page":
$which = (is_front_page() && !is_home()) ? "page" : "paged";
$page = isset($this->qv[$which]) ? intval($this->qv[$which]) : 0;
return $page;
}
}
public function title() {
the_title();
}
public function titleAttribute() {
the_title_attribute();
}
public function getLink() {
$link = get_permalink();
global $post;
if (isset($post) && $post->post_type === "attachment") {
$link = $this->get_origImage();
}
return $link;
}
public function link() {
echo $this->get_link();
}
public function twitterShareLink() {
$link = "http://twitter.com/home?status=";
$link .= urlencode(get_the_title()." - ");
$link .= get_permalink();
echo esc_attr($link);
}
public function facebookShareLink() {
$link = "http://www.facebook.com/sharer/sharer.php?u=";
$link .= get_permalink();
echo esc_attr($link);
}
public function filter($tax,$sep = "",$aclass="label",$template = '%s') {
if (is_array($tax) && isset($tax[1]) && is_a($tax[1],"PeThemeDataLoop")) {
$loop = $tax[1]->main->loop;
$ids = array();
$n = count($loop);
for($i=0;$i<$n;$i++) {
$ids[] = $loop[$i]->id;
}
$terms = wp_get_object_terms($ids,$tax[0]);
} else if ($this->have_posts()) {
$ftax = in_array($tax,array('post_tag','category')) ? strtr($tax,array('post_tag'=>'tag','category' => 'category_name')) : $tax;
if (!empty($this->wpq->query[$ftax])) {
$slugs = explode(",",$this->wpq->query[$ftax]);
$terms = array();
if (!empty($slugs)) {
foreach ($slugs as $slug) {
$term = get_term_by('slug',$slug,$tax);
if (!empty($term) && !empty($term->term_id)) {
$terms[] = $term;
}
}
}
} else {
$posts =& $this->wpq->posts;
$ids = array();
$n = count($posts);
for($i=0;$i<$n;$i++) {
$ids[] = $posts[$i]->ID;
}
$terms = wp_get_object_terms($ids,$tax);
}
} else {
$terms = array();
}
$seen = array();
// to get all terms
//$terms = get_terms($tax);
$output = "";
$buffer = "";
if (is_array($terms) && count($terms) > 0) {
$buffer = apply_filters("pe_theme_filter_item",sprintf('<a class="%s active" data-category="" href="#">%s</a>%s',$aclass,__("All",'Pixelentity Theme/Plugin'),"$sep\n"),$aclass,"",__("All",'Pixelentity Theme/Plugin'));
$output = sprintf($template,$buffer);
foreach ($terms as $term) {
$id = $term->term_id;
if (isset($seen[$id])) continue;
$seen[$id] = true;
$buffer = apply_filters("pe_theme_filter_item",sprintf('<a class="%s" data-category="%s" href="#">%s</a>%s',$aclass,$term->slug,$term->name,"$sep\n"),$aclass,$term->slug,$term->name);
$output .= sprintf($template,$buffer);
}
print $output;
}
}
public function filterClasses($tax,$id = null) {
if (empty($tax)) return;
if (empty($id)) {
global $post;
$id = $post->ID;
}
$classes = wp_get_post_terms($id,$tax,array("fields" => "slugs"));
if (is_array($classes) && ($count = count($classes)) > 0) {
while($count--) {
$classes[$count] = "filter-".$classes[$count];
}
echo join(" ",$classes);
}
}
public function thumb($useFilters = true) {
global $post;
if (has_post_thumbnail()) {
$thumb = get_the_post_thumbnail($post->ID,"thumbnail");
if ($useFilters && has_filter("pe_post_thumbnail")) {
echo apply_filters("pe_post_thumbnail",$thumb);
} else {
echo $thumb;
}
}
}
public function post_thumbnail_filter($data) {
return $data;
}
public function hasFeatImage() {
global $post;
return #has_post_thumbnail($post->ID);
}
public function get_origImage($id = null) {
return wp_get_attachment_url(get_post_thumbnail_id($id));
}
public function resizedImg($w,$h,$custom = null) {
$url = empty($custom) ? wp_get_attachment_url(get_post_thumbnail_id()) : $custom;
return $this->master->image->resizedImg($url,$w,$h);
}
public function img($w,$h = null,$custom = null) {
$img = $this->resizedImg($w,$h,$custom);
echo apply_filters("pe_theme_content_img",$img ? $img : "",$w,$h);
}
public function get_thumbImage($thumb) {
if (#has_post_thumbnail()) {
$thumb = wp_get_attachment_image_src(get_post_thumbnail_id(),$thumb);
return $thumb[0];
}
return "";
}
public function origImage() {
echo $this->get_origImage();
}
public function excerpt() {
the_excerpt();
}
public function content($text = null) {
global $post;
if (isset($post) && $post->post_type === "attachment") {
echo apply_filters("wpautop",$post->post_excerpt);
} else {
the_content($text);
}
}
public function builder() {
if (post_password_required() || !PE_THEME_PLUGIN) {
$this->content();
} else {
$meta =& $this->meta();
if (empty($meta->builder)) return;
global $post;
$view = new PeThemeViewLayout();
$conf = (object)
array(
"id" => $post->ID,
"settings" => $meta->builder
);
$view->output($conf);
}
}
public function hasMedia() {
$format = $this->format();
$meta =& $this->meta();
$ret = false;
switch ($format) {
case "gallery":
$gallery = empty($meta->gallery) ? false : $meta->gallery;
$ret = !empty($gallery->id) && $gallery->id > 0;
break;
case "video":
$video = empty($meta->video) ? false : $meta->video;
$ret = !empty($video->id) && $video->id > 0;
break;
default:
$ret = $this->hasFeatImage();
}
return $ret;
}
public function slider($w,$h) {
if ($this->format() != "gallery") return;
$meta =& $this->meta();
$gallery = empty($meta->gallery) ? false : $meta->gallery;
if (empty($gallery->id)) return;
$view =& $this->master->view;
$conf = $view->create("SliderVolo","gallery",array("id" =>$gallery->id),$w,$h);
$view->resize($conf);
}
public function media() {
$format = $this->format();
$meta =& $this->meta();
switch ($format) {
case "gallery":
$gallery = empty($meta->gallery) ? false : $meta->gallery;
if (!empty($gallery->id)) {
$conf =
$this->master->view->create(
$gallery->type,
"gallery",
array("id" => $gallery->id),
$gallery->width,
$gallery->height
);
// use gallery caption
$conf->caption = (object) array("title" => "ititle","description" => "caption");
//$conf->caption->title = "ititle";
//$conf->caption->description = "caption";
$this->master->view->resize($conf);
}
break;
case "video":
$this->master->video->output();
break;
default:
$format = $this->hasFeatImage() ? "image" : false;
}
return $format;
}
public function current($add = 0) {
$page = $this->page;
if ($page > 1) {
$add += $this->qv["posts_per_page"]*($page-1);
}
echo $this->wpq->current_post + $add;
}
public function terms($tax,$sep = ",") {
global $post;
return join($sep,wp_get_post_terms($post->ID,$tax,array("fields" => "names")));
}
public function &getPostsQueryArgs($type,$count,$tax = null,$custom = null,$paged = false) {
$args = array(
"post_type"=>"$type",
"posts_per_page"=>$count
);
if ($tax) {
$custom[$tax] = $this->terms($tax);
}
if (is_array($custom)) {
$args = array_merge($args,$custom);
}
if ($paged) {
$page = $this->page;
$page = $page ? $page - 1 : 0;
$args["offset"] = $count*$page;
} else {
// if pagination is not needed, avoid counting rows to boost performances
$args['no_found_rows'] = true;
}
if ($args["post_type"] === "attachment") {
$args["post_status"] = "inherit";
}
return $args;
}
public function getPostsLoop($type,$count,$tax = null,$custom = null,$paged = false) {
$data = new StdClass();
$args =& $this->getPostsQueryArgs($type,$count,$tax,$custom,$paged);
$wpq = new WP_Query();
$data->loop = $wpq->query($args);
$loop =& $this->master->data->create($data,true);
if ($paged) {
$loop->pages = $wpq->max_num_pages;
}
return $loop;
}
public function customLoop($type,$count = 10,$tax = null,$custom = null,$paged = false) {
$args =& $this->getPostsQueryArgs($type,$count,$tax,$custom,$paged);
if ($this->current) {
$this->loops[] = $this->current;
}
$this->master->data->postSave();
$this->current = new WP_Query($args);
return $this->current->post_count > 0;
}
public function related($type,$tax,$count) {
//$settings = new StdClass();
//$settings->post_type = "project";
if ($loop = $this->customLoop($type,$count,$tax)) {
get_template_part("related",$type);
$this->resetLoop();
}
}
public function resetLoop() {
$this->master->data->postReset();
$this->current = (count($this->loops) >0) ? array_pop($this->loops) : false;
}
public function blog($settings,$showpager = true) {
global $post;
$exclude = false;
// prevents nested blogs
if ($this->blogLoop) return;
$this->blogLoop = true;
// prevents loops
if (isset($post) && $post) {
$exclude = $post->ID;
}
if (is_string($settings) && !empty($settings)) {
$id = $settings;
$post = get_post($id);
if (!$post) return;
$meta = $this->master->meta->get($id,$post->post_type);
if (empty($meta->blog)) return true;
$settings = $meta->blog;
}
$settings = (object) shortcode_atts(
array(
"layout" => "",
"count" => get_option("posts_per_page"),
"media" => "yes",
"pager" => "yes",
"sticky" => "yes",
"category" => "",
"tag" => "",
"format" => ""
),
(array) $settings
);
// prevents loops
if ($exclude) {
$custom = array("post__not_in" => array($exclude));
}
$custom["ignore_sticky_posts"] = ($settings->sticky === "no") ? 1 : 0;
if ($settings->category) {
$custom["category_name"] = $settings->category;
}
if ($settings->tag) {
$custom["tag"] = $settings->tag;
}
if ($settings->format) {
$tax_query = array(
array(
'taxonomy' => 'post_format',
'field' => 'slug',
'terms' => array("post-format-{$settings->format}")
)
);
$custom["tax_query"] = $tax_query;
}
$media = $settings->media === "yes";
$this->customLoop("post",$settings->count,null,$custom,$settings->pager === "yes");
$compact = compact("media");
$this->master->template->get_part($compact,"loop",$this->have_posts() ? $settings->layout : "empty");
if ($showpager && $settings->pager === "yes") {
$this->pager();
}
$this->resetLoop();
$this->blogLoop = false;
}
public function getPagerLoop($max = 5,$pages = false) {
$pages = $pages ? $pages : $this->wpq->max_num_pages;
if ($pages <= 1) return false;
for ($p = 0;$p<$pages;$p++) {
$links[] = get_pagenum_link($p+1);
}
return $this->master->data->createPager($this->page,$links,$max);
}
public function pager($class = "span12",$pages = false) {
$loop = $this->getPagerLoop(5,$pages);
if ($loop) $loop->main->class = $class;
$this->master->template->paginate_links($loop);
}
public function comments() {
comments_number('0','1','%');
}
public function body_class($class = "") {
echo 'class="' . apply_filters("pe_theme_body_class",join( ' ', get_body_class( $class ) )) . '"';
}
public function total() {
echo $this->wpq->found_posts;
}
public function hasNextPage() {
$max = $this->wpq->max_num_pages;
return ($max > 1 && $this->page < $max);
}
public function hasPrevPage() {
$max = $this->wpq->max_num_pages;
return ($max > 1 && $this->page > 1);
}
public function tagCloud($number,$orderby="name") {
wp_tag_cloud(array("number"=>$number,"orderby"=>$orderby,"order"=>$orderby == "count" ? "DESC" : "ASC"));
}
public function tags($sep = ", ",$tax = false) {
if ($tax) {
echo get_the_term_list(null, $tax, "", $sep, "");
} else {
the_tags("",$sep,"");
}
}
public function category($prefix="") {
if ($prefix) {
echo "$prefix ";
}
the_category(", ");
}
public function date($prefix="") {
if ($prefix) {
echo "$prefix ";
}
the_time(get_option('date_format'));
}
public function author($prefix="") {
if ($prefix) {
echo "$prefix ";
}
the_author();
}
public function format($is_format = null) {
global $post;
$format = get_post_format($post->ID);
return empty($is_format) ? $format : $format === $is_format;
}
public function pageTemplate($post_id = null) {
if (function_exists("get_page_template_slug")) return get_page_template_slug($post_id);
$post = get_post( $post_id );
if ( 'page' != $post->post_type )
return false;
$template = get_post_meta( $post->ID, '_wp_page_template', true );
if ( ! $template || 'default' == $template )
return '';
}
public function slug() {
global $post;
echo $post->post_name;
}
public function type() {
global $post;
return $post->post_type;
}
public function classes($add="") {
$c = join(" ",get_post_class());
$c = $add ? "$c $add" : "$c";
printf('class="%s"',$c);
}
public function isVideo() {
return get_post_format() === "video";
}
public function includeLoopPart($prefix="looped") {
global $post;
$type = $post->post_type;
get_template_part("$prefix-$type",$this->format());
}
public function getBlogLink() {
$pfp = get_option("page_for_posts");
$pfp = $pfp ? get_page_link($pfp) : "";
return get_option('show_on_front') == 'page' ? $pfp : home_url();
}
public function wp_tag_cloud_filter($data) {
if (is_tag()) {
global $wp_query;
$currentTagID = $wp_query->get_queried_object()->term_id;
$data = str_replace("tag-link-$currentTagID","tag-link-$currentTagID current-tag",$data);
}
return preg_replace('/style=.[^"|\']+./i','',$data);
}
public function widget_tag_cloud_args_filter($args) {
$options =& $this->master->options;
$orderby = $options->get("tagCloudOrder");
$args = array_merge($args,array("number"=>$options->get("tagCloudCount"),"orderby"=>$orderby,"order"=>$orderby == "count" ? "DESC" : "ASC"));
return $args;
}
public function &meta($postID = FALSE) {
global $post;
//print_r($post);
return $this->master->meta->get($postID ? $postID : ($post ? $post->ID : NULL),$post ? $post->post_type : "post");
}
public function strip_rel_filter($content) {
return preg_replace('/rel="/','data-rel="',$content);
}
public function excerpt_more_filter($more) {
return "";
}
public function the_content_more_link_filter($link) {
//$link = sprintf(' %s',get_permalink(),$GLOBALS["post"]->ID,__("more",'Pixelentity Theme/Plugin'));
$link = sprintf(' %s',get_permalink(),__("more",'Pixelentity Theme/Plugin'));
return $link;
}
public function edit_post_link_filter($link) {
return str_replace("post-edit-link","label",$link);
}
public function getSocialLinks($links,$position = "top") {
$html = "";
if (is_array($links)) {
foreach ($links as $link) {
if (empty($link)) continue;
list($icon,$tooltip) = explode("|",$link["icon"]);
$html .= apply_filters("pe_theme_content_get_social_link",sprintf('<i class="%s"></i>',$link["url"],$position,$tooltip,$icon),$link["url"],$tooltip,$icon);
}
}
return $html;
}
public function socialLinks($links,$position = "top") {
$html = apply_filters("pe_theme_social_links",$this->getSocialLinks($links,$position),$position);
echo $html ? $html : "";
}
public function getPagesByTemplate($template) {
$args = array();
if ($template) {
$args =
array(
'meta_key' => '_wp_page_template',
'meta_value' => "page-$template.php"
);
}
$pages = get_pages($args);
return $pages;
}
public function getPagesLinkByTemplate($template) {
$pages = $this->getPagesByTemplate($template);
if (!is_array($pages)) return false;
$links = false;
foreach ($pages as $page) {
$links[] = get_page_link($page->ID);
}
return $links;
}
public function getPagesOptionsByTemplate($template) {
$pages = $this->getPagesByTemplate($template);
if (!is_array($pages)) return false;
$links = false;
foreach ($pages as $page) {
$links[$page->post_title] = $page->ID;
}
return $links;
}
public function getPageLinkByTemplate($template) {
$pages = $this->getPagesLinkByTemplate($template);
return $pages ? $pages[0] : "";
}
public function adjPost($previous = false) {
$post = get_adjacent_post(false,"", $previous);
$ret = "";
if ($post) {
$ret = new StdClass;
$ret->title = get_the_title($post);
$ret->link = get_permalink($post);
$ret->date = get_the_time(get_option('date_format'), $post);
}
return $ret;
}
public function breadcrumbs($sep = ' / ') {
$template = '<a class="pe-breadcrumbs-%s" href="%s">%s</a>';
$links[] = sprintf($template,'home',home_url(),__('Home','Pixelentity Theme/Plugin'));
if (is_home()) {
$links[] = sprintf($template,'blog','#',__('Blog','Pixelentity Theme/Plugin'));
} elseif (is_category()) {
$links[] = substr(get_category_parents(get_query_var('cat'),true,$sep), 0, -strlen($sep));
} elseif (is_tag() || is_tax()) {
$term = get_queried_object();
if (!empty($term->term_id)) {
$links[] = sprintf($template,'tax',get_tag_link($term->term_id),single_term_title("",false));
}
} elseif (is_archive()) {
if ( is_day() ) {
$date = get_the_date();
} elseif ( is_month() ) {
$date = get_the_date('F Y');
} elseif ( is_year() ) {
$date = get_the_date('Y');
} else {
$date = __("Archives",'Pixelentity Theme/Plugin');
}
$links[] = sprintf($template,'archive','#',$date);
} elseif (is_page()) {
global $post;
if (!empty($post->ID)) {
$parents = get_post_ancestors($post->ID);
if (!empty($parents) && is_array($parents)) {
$parents = array_reverse($parents);
$parents[] = $post->ID;
$home = trailingslashit(home_url());
foreach ($parents as $id) {
$link = get_permalink($id);
if ($link == $home) continue;
$links[] = sprintf($template,'page',$link,get_the_title($id));
}
}
}
} elseif (is_single()) {
global $post;
if (!empty($post->ID)) {
$taxs = get_object_taxonomies($post,"names");
if (!empty($taxs) && is_array($taxs)) {
while ($tax = array_shift($taxs)) {
if ($tax != "post_format") break;
}
if ($tax) {
$terms = get_the_terms($post->ID,$tax);
if (is_array($terms)) {
reset($terms);
$term = key($terms);
$parents = get_ancestors($terms[$term]->term_id,$tax);
$parents = is_array($parents) ? array_reverse($parents) : array();
$parents[] = $terms[$term]->term_id;
foreach ($parents as $id) {
$term = get_term($id,$tax);
$links[] = sprintf($template,'tax',get_term_link($term),$term->name);
}
}
}
}
$links[] = sprintf($template,'single',get_permalink($post->ID),get_the_title($post->ID));
}
}
print join($links,$sep);
}
public function adjPostLink($previous = false) {
$post = get_adjacent_post(false,"", $previous);
return $post ? get_permalink($post) : "";
}
public function prevPostLink() {
return $this->adjPostLink(true);
}
public function nextPostLink() {
return $this->adjPostLink(false);
}
public function linkPages() {
wp_link_pages(array('before' => '<div class="page-links">' . __('Pages:','Pixelentity Theme/Plugin'), 'after' => '</div>'));
}
}
?>

Create my own entity generator on symfony using doctrine generator

I am building an entity generator in order to update my DB's structure and data according to a distant one (DB), via SOAP WS...
I get the structure from an array, and am currently writing my entity classes by myself, with a file_put_content().
But as I advance, I can't help noticing that the Doctrine\ORM\Tools\EntityGenerator already does what I intend to do, way better I would ever be able to!!
So i was wondering if there was a way to use this implemented generator from my controller?
I mean, this is what Symfony is all about right? Using existing classes & bundles from anywhere in my code? :)
Any idea someOne?
Thx :)
You can use this code:
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpKernel\Bundle\BundleInterface;
use Sensio\Bundle\GeneratorBundle\Generator\DoctrineEntityGenerator;
use Sensio\Bundle\GeneratorBundle\Command\Validators;
class MyController extends Controller
{
private $generator;
public function generateEntityAction()
{
$format = "annotation"; //it can also be yml/php/xml
$fields = "title:string(255) body:text";
$withRepository = false; //true/false
$entity = Validators::validateEntityName("MyBundle:EntityName");
list($bundle, $entity) = $this->parseShortcutNotation($entity);
$format = Validators::validateFormat($format);
$fields = $this->parseFields($fields);
$bundle = $this->get('service_container')->get('kernel')->getBundle($bundle);
$generator = $this->getGenerator();
$generator->generate($bundle, $entity, $format, array_values($fields), $withRepository);
}
protected function createGenerator()
{
return new DoctrineEntityGenerator($this->get('service_container')->get('filesystem'), $this->get('service_container')->get('doctrine'));
}
protected function getSkeletonDirs(BundleInterface $bundle = null)
{
$skeletonDirs = array();
if (isset($bundle) && is_dir($dir = $bundle->getPath() . '/Resources/SensioGeneratorBundle/skeleton')) {
$skeletonDirs[] = $dir;
}
if (is_dir($dir = $this->get('service_container')->get('kernel')->getRootdir() . '/Resources/SensioGeneratorBundle/skeleton')) {
$skeletonDirs[] = $dir;
}
$skeletonDirs[] = __DIR__ . '/../Resources/skeleton';
$skeletonDirs[] = __DIR__ . '/../Resources';
return $skeletonDirs;
}
protected function getGenerator(BundleInterface $bundle = null)
{
if (null === $this->generator) {
$this->generator = $this->createGenerator();
$this->generator->setSkeletonDirs($this->getSkeletonDirs($bundle));
}
return $this->generator;
}
protected function parseShortcutNotation($shortcut)
{
$entity = str_replace('/', '\\', $shortcut);
if (false === $pos = strpos($entity, ':')) {
throw new \InvalidArgumentException(sprintf('The entity name must contain a : ("%s" given, expecting something like AcmeBlogBundle:Blog/Post)', $entity));
}
return array(substr($entity, 0, $pos), substr($entity, $pos + 1));
}
private function parseFields($input)
{
if (is_array($input)) {
return $input;
}
$fields = array();
foreach (explode(' ', $input) as $value) {
$elements = explode(':', $value);
$name = $elements[0];
if (strlen($name)) {
$type = isset($elements[1]) ? $elements[1] : 'string';
preg_match_all('/(.*)\((.*)\)/', $type, $matches);
$type = isset($matches[1][0]) ? $matches[1][0] : $type;
$length = isset($matches[2][0]) ? $matches[2][0] : null;
$fields[$name] = array('fieldName' => $name, 'type' => $type, 'length' => $length);
}
}
return $fields;
}
}
Mostly, it comes from Sensio\Bundle\GeneratorBundle\Command\GenerateDoctrineEntityCommand and Sensio\Bundle\GeneratorBundle\Command\GeneratorCommand

in zend framework 2 how to save fieldset data to database

I just start to study zend framwork2 , and read the document about how to use fieldset http://zf2.readthedocs.org/en/latest/modules/zend.form.collections.html
I can use tablegateway insert product data into database.but don't know how to insert data to brand table and I don't know how to link product and brand . thank you very much!!!!!
Many people has the same problem and rlandas wrote and uploaded a working code to github
i post the code of the controller in case the url changes. but take a look at the complete module in github
<?php
namespace Product\Controller;
use Product\Table\ProductTable;
use Product\Entity\Product as ProductEntity;
use Product\Form\CreateProduct;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\Http\PhpEnvironment\Response;
use Zend\View\Model\ViewModel;
class ManageController extends AbstractActionController
{
public function indexAction ()
{
$product = $this->getProductTable();
$products = $product->getAllOrderByName();
$view = new ViewModel();
$view->setVariable('products', $products);
return $view;
}
public function viewAction ()
{
if ($id = $this->params('id')) {
$product = $this->getProductTable()
->getByProductId($id);
}
$view = new ViewModel();
$view->setVariable('product', $product);
return $view;
}
public function addAction ()
{
$form = new CreateProduct();
$product = $this->getServiceLocator()->get('Product\Entity\Product');
$form->bind($product);
$data = array(
'product' => array(
'name' => 'product name ' . mt_rand(1, 1000),
'price' => mt_rand(100.000, 5000.999) / 100,
'brand' => array(
'name' => 'My brand ' . mt_rand(1, 200),
'url' => 'http://www.mybrand.com'
),
'categories' => array(
array('name' => 'Sony'),
array('name' => 'Panasonic'),
array('name' => 'Phillips')
)
)
);
$form->populateValues($data);
// action viewscript
$view = new ViewModel(array(
'form' => $form
));
// do Post/Redirect/Get (PRG) strategy to stop user refresh/back button
$prg = $this->prg($this->getRequest()->getRequestUri(), true);
if ($prg instanceof Response) {
return $prg;
}
// this is when the user first arrives to this url, display the form
else if ($prg === false) {
return $view;
}
// lets retrieve the post data stored in the PRG session
$post = $prg;
// validate the form
$form->setData($post);
if(!$form->isValid())
return $view;
// if data are valid, then save
// save the brand
$brand = $product->getBrand();
$brandTable = $this->getBrandTable();
$brand = $brandTable->save($brand);
$brandId = $brandTable->getLastInsertValue();
$product->setBrandId($brandId);
// save the categories
$categoryTable = $this->getCategoryTable();
$categoryTable->persist($product->getCategories())->flush();
$categoryIds = implode(",", $categoryTable->getEntityIds());
$product->setCategoryIds($categoryIds);
// save the product
$productTable = $this->getProductTable();
$product = $productTable->save($product);
$this->redirect()->toRoute('product');
return $view;
}
public function editAction ()
{
$form = new CreateProduct();
$product = $this->getServiceLocator()->get('Product\Entity\Product');
$form->bind($product);
// action viewscript
$view = new ViewModel(array(
'form' => $form
));
$productTable = $this->getProductTable();
if ($id = $this->params('id')) {
$product = $this->getProductTable()->getByProductId($id);
// get the brands
$brand = $this->getBrandTable()->getByBrandId($product->getBrandId());
$product->setBrand($brand);
// get the categories
$categoryIds = explode(",", $product->getCategoryIds());
$categories = $this->getCategoryTable()->getAllByCategoryId($categoryIds);
$product->setCategories($categories);
$form->bind($product);
}
// do Post/Redirect/Get (PRG) strategy to stop user refresh/back button
$prg = $this->prg($this->getRequest()->getRequestUri(), true);
if ($prg instanceof Response) {
return $prg;
}
// this is when the user first arrives to this url, display the form
else if ($prg === false) {
return $view;
}
// lets retrieve the post data stored in the PRG session
$post = $prg;
// validate the form
$form->setData($post);
if(!$form->isValid())
return $view;
\Zend\Debug\Debug::dump(__METHOD__.' '.__LINE__);
\Zend\Debug\Debug::dump($post);
\Zend\Debug\Debug::dump($product);
return $view;
}
/**
*
* #return \Product\Table\ProductTable
*/
public function getProductTable ()
{
$sm = $this->getServiceLocator();
$table = $sm->get('Product\Table\ProductTable');
return $table;
}
/**
*
* #return \Product\Table\BrandTable
*/
public function getBrandTable ()
{
return $this->getServiceLocator()
->get('Product\Table\BrandTable');
}
/**
*
* #return \Product\Table\CategoryTable
*/
public function getCategoryTable ()
{
return $this->getServiceLocator()
->get('Product\Table\CategoryTable');
}
}

Extend wpdb in other class - when use get_results for select gives me null

I've added custom plugin (created by me) in WP in that plugin I have Class named BaseModel, which extends wpdb.
The problem here is everytime when I try to run query I get false or null or empty array as result.
class BaseModel extends wpdb{
public function __construct(){
parent::__construct(DB_HOST, DB_USER, DB_PASS, DB_NAME);
}
function get_destinations($limit, $order){
$query = "SELECT * FROM wp_relations";
$result = $this->get_results($query, ARRAY_A);
var_dump($result);
}
function get_total_destinations(){
}}
Can some one tell me what is wrong?
Thanks.
Actually it is not a full OOP solution but I solve this by adding global $wpdb into my functions.
class BaseModel {
function get_destinations($limit, $order){
global $wpdb;
$query = "SELECT * FROM wp_relations";
$result = $wpdb->get_results($query, ARRAY_A);
var_dump($result);
}
function get_total_destinations(){
}}
I hope you will find this helpful.
More Info WordPress tests with wpdb
<?php
class testWPDB extends wpdb {
function prepare( $query, $arguments ){
return vsprintf( $query, $arguments );
}
}
class UTCW_Test_Data extends WP_UnitTestCase {
protected $utcw;
function setUp(){
$this->utcw = UTCW_Plugin::get_instance();
}
function getWPDBMock(){
return $this->getMock( 'testWPDB', array( 'get_results' ), array(), '', false );
}
function test_author(){
$instance[ 'authors' ] = array( 1, 2, 3 );
$config = new UTCW_Config( $instance, $this->utcw );
$db = $this->getWPDBMock( 'get_results' );
$db->expects( $this->once() )
->method( 'get_results' )
->with( $this->stringContains( 'post_author IN (1,2,3)' ) );
$data = new UTCW_Data( $config, $db );
$data->get_terms();
}
}
I dont think you want to extend from it? If this class will always be loaded inside Wordpress files then you will have access to the global $wpdb.
class RandomClass {
private $wpdb = false;
public function __construct() {
global $wpdb;
if (is_object($wpdb)) {
$this->wpdb = $wpdb;
}
}
public function get_results($data) {
return $this->wpdb->get_results($data);
}
}

How to handle in a generic way the session storage of filters avoiding the "Entity must be managed"

We've all been confronted to that problem : "Entity must be managed" when we are trying to setFilters() / getFilters()
So how to handle the session storage of filters in a generic way, in order to avoid merging and detaching or re-hydrating manually the entities ?
See the answer just below.
Well, some colleague (#benji07) at work have written this :
/**
* Set filters
* #param string $name Name of the key to store filters
* #param array $filters Filters
*/
public function setFilters($name, array $filters = array())
{
foreach ($filters as $key => $value) {
// Transform entities objects into a pair of class/id
if (is_object($value)) {
if ($value instanceof ArrayCollection) {
if (count($value)) {
$filters[$key] = array(
'class' => get_class($value->first()),
'ids' => array()
);
foreach ($value as $v) {
$identifier = $this->getDoctrine()->getEntityManager()->getUnitOfWork()->getEntityIdentifier($v);
$filters[$key]['ids'][] = $identifier['id'];
}
}
}
elseif (!$value instanceof \DateTime) {
$filters[$key] = array(
'class' => get_class($value),
'id' => $this->getDoctrine()->getEntityManager()->getUnitOfWork()->getEntityIdentifier($value)
);
}
}
}
$this->getRequest()->getSession()->set(
$name,
$filters
);
}
/**
* Get Filters
* #param string $name Name of the key to get filters
* #param array $filters Filters
*
* #return array
*/
public function getFilters($name, array $filters = array())
{
$filters = array_merge(
$this->getRequest()->getSession()->get(
$name,
array()
),
$filters
);
foreach ($filters as $key => $value) {
// Get entities from pair of class/id
if (is_array($value) && isset($value['class']) && isset($value['id'])) {
$filters[$key] = $this->getDoctrine()->getEntityManager()->find($value['class'], $value['id']);
} elseif (isset($value['ids'])) {
$data = $this->getDoctrine()->getEntityManager()->getRepository($value['class'])->findBy(array('id' => $value['ids']));
$filters[$key] = new ArrayCollection($data);
}
}
return $filters;
}
It works for basic entities, and multivalued choices
PS: Don't forget to add a use statement for the ArrayCollection
Disclaimer, we don't know if it's a good practice, and we know at least one limitation : you have to be sure that the object you try to save in the session has an id (it's 99,9% the case)

Resources