This question already has answers here:
Constructor in PHP
(2 answers)
Closed 14 days ago.
I have the following code in 7.4 it worked for me now in 8.1 it doesn't work for me...
I corrected it by replacing foreach but I still have errors of
Undefined property: Plantilla::$mihtml
help please
I hope you can help me I don't know how to solve this problem
<?php
class Plantilla{
function Plantilla($template_file){
$this->tpl_file =$template_file ;
}
function asigna_variables($vars){
$this->vars= (empty($this->vars)) ? $vars : $this->vars . $vars;
}
function muestra(){
$this->template_file = $this->tpl_file;
$this->mihtml = $this->template_file;
$this->mihtml = str_replace ("'", "\'", $this->mihtml);
$this->mihtml = preg_replace('#\{([a-z0-9\-_]*?)\}#is', "' . $\\1 . '", $this->mihtml);
reset ($this->vars);
foreach($this->vars as $key => $val) {
$$key = $val;
}
eval("\$this->mihtml = '$this->mihtml';");
reset ($this->vars);
foreach($this->vars as $key => $val)
{
unset($$key);
}
$this->mihtml=str_replace ("\'", "'", $this->mihtml);
return $this->mihtml;
//AQUI SI QUEREMOS USARDEFRENTE EN PARA MOSTTRAR SE DEBE CAMBIAR A ''ECHO'
}
}
$COD_RANDOM ='1234567899999999999999999999999999999999999';
$Contenido=new Plantilla('el codigo es {CODIGO_RANDOM}');//al Pasar como parametro Prueba, asumimos que en la carpeta plantillas existe un archivo de nombre Prueba.tpl
$Contenido->asigna_variables(array(
"CODIGO_RANDOM" => $COD_RANDOM //codigo generado
));
#$ContenidoString = $Contenido->muestra();//$ContenidoString contiene nuestra plantilla, ya con las variables asignadas, fácil no?
$mensajebody=$Contenido->muestra();
echo $mensajebody;
?> ```
espero me puedan ayudar por favor
You are giving $template when you create an $Contenido object.
new Plantilla('el codigo es {CODIGO_RANDOM}');
You mean it to be set as local property of class. But the construction function in PHP calls not by class name, but with special name __construct()
The code of class should start with the following
class Plantilla
{
function __construct($template_file) //<-- this function name changes
{
$this->tpl_file = $template_file;
}
}
Please, follow this manual: https://www.php.net/manual/en/language.oop5.decon.php
Related
I have a table where I drag and drop, when I drop the row I want to update order values, it works but start updating from value 0 and I want start from 1.
Example before drag and drop:
After:
My code looks like here:
public function updateOrder(Request $request)
{
$queryParams = [];
$ids = $request->ids;
//el query será definido en su totalidad de forma manual
$query = 'UPDATE projects SET `order` = CASE id ';
//agregamos cada parámetro de orden y de id al array para respetar las convenciones de PDO
foreach ($ids as $order => $id) {
$query .= 'WHEN ? THEN ? ';
$queryParams[] = (int) $id;
$queryParams[] = (int) $order;
}
//por último agregamos los ids implicados en el update
$queryParams = array_merge($queryParams, $ids);
//generamos los ? necesarios para el array de ids en el query PDO
$whereInArray = array_fill(0, count($ids), '?');
$whereInString = implode(", ", $whereInArray);
//agregamos dicho string generado al query final
$query .= "END WHERE id IN ($whereInString)";
//realizamos el update
DB::update($query, $queryParams);
}
¿What I need to update in code?
Please try $queryParams[] = (int) $order+1;
I have a little problem, I'm getting around 800 000 datas from a json and I'm trying to insert them into a MongoDB Database. But I reach memory limit (I've set it up to 8GB for testing) while doing this. I think my script isn't optimized but I can't find where. Can you guys help me ? Here is the script :
$jsonResponse = json_decode($content->response);
$datas = $jsonResponse->hits->hits;
// On crée la collection si elle n'éxiste pas
$collection = $connection->createCollection($table->getTableName(), false );
// On enregistre les données dans la collection
foreach ($datas as $data)
{
if(!empty($data) || $data)
{
$document['_id'] = $data->_id; // ID netwoof unique
$document['_updated'] = substr($data->_source->_updated, 0, -3); // Date de dernière MàJ des données
$document['_url'] = $data->_source->_url; // Start URL
// On enregistre ensuite chaque champs définis dans le dashboard
foreach ($fields as $field)
{
// On récupère le nom du champs netwoof
$containerFieldName = $field->getContainerFieldName();
// On fait correspondre notre champ db avec celui netwoof
if( isset( $data->_source->$containerFieldName ) && (!empty($data->_source->$containerFieldName) || $data->_source->$containerFieldName == 0 ) )
$document[$field->getFieldName()] = $data->_source->$containerFieldName;
/*else
$document[$field->getFieldName()] = null;*/
}
foreach ($customFields as $customField)
{
if(!empty($customField->getFieldValue()))
$document[$customField->getFieldName()] = $customField->getFieldValue();
}
// Enregistrement des données
$collection->save($document);
}
// On réinitialise la variable
unset($document);
}
Thanks all for your answer and sorry for my english.
I will try to explain my case.
I would like to change the wpseo_title, wpseo_metakey, wpseo_metadesc, wpseo_opengraph_type, wpseo_opengraph_image, wpseo_title, and wpseo_opengraph_image_size on the "archive-page" of "custom post"
Because yoast plugin not translated meta tags inside "archive" post. And i need to translate all
I have this code:
function get_archive_seo() {
include 'seo_archive.php';
$tipoSel = get_post_type(get_the_ID());
if(is_post_type_archive( $tipoSel )){
foreach ($traduccionesArchive as $keyTipo => $tipo){
foreach ($tipo as $keyMeta => $palabra){
if($keyMeta == 'opengraph_type' || $keyMeta == 'opengraph_image_size') continue;
icl_register_string ('my-theme', $keyTipo." - ".$keyMeta, $palabra);
}
}
foreach ($traduccionesArchive[$tipoSel] as $key => $palabra){
add_filter( 'wpseo_'.$key, function($nombre) use ( $palabra, $tipoSel, $key ) {
if($key == 'opengraph_type' || $key == 'opengraph_image_size') return $palabra;
return icl_t('my-theme', $tipoSel." - ".$key, $palabra);
});
}
}
}
add_filter( 'wp_head', 'get_archive_seo');
And this is the "seo_archive.php":
$traduccionesArchive['hoteles']['title'] = 'Hotel, Vacaciones en Andalucia';
$traduccionesArchive['hoteles']['metakey'] = 'palabra1, palabra2, palabra3';
$traduccionesArchive['hoteles']['metadesc'] = 'Mapa de Hotel en Andalucia, Costa del Sol, Costa de la Luz y Sierra de Grazalema. El lugar ideal para tus vacaciones.';
$traduccionesArchive['hoteles']['opengraph_type'] = 'object';
$traduccionesArchive['hoteles']['opengraph_image'] = 'http://www.hotel.com/img/logo.png';
$traduccionesArchive['hoteles']['opengraph_image_size'] = 100;
$traduccionesArchive['apartamentos']['title'] = 'Apartamentos de vacaciones Costa del Sol ';
$traduccionesArchive['apartamentos']['metakey'] = 'palabra1, palabra2, palabra3';
$traduccionesArchive['apartamentos']['metadesc'] = 'Mapa de localizacion de los Apartamentos Vacacionales de Hotel. Disfruta de tus vacaciones en familia en la Costa del Sol.';
$traduccionesArchive['apartamentos']['opengraph_type'] = 'object';
$traduccionesArchive['apartamentos']['opengraph_image'] = 'http://www.hotel.com/img/logo.png';
$traduccionesArchive['apartamentos']['opengraph_image_size'] = 100;
$traduccionesArchive['destinos']['title'] = 'Mapa de localizacion de Hotel, Andalucia';
$traduccionesArchive['destinos']['metakey'] = 'palabra1, palabra2, palabra3';
$traduccionesArchive['destinos']['metadesc'] = 'Mapa de Hoteles en Andalucia, en los destinos vacacionales de Costa del Sol, Costa de la Luz y Sierra de Grazalema Andalucia.';
$traduccionesArchive['destinos']['opengraph_type'] = 'object';
$traduccionesArchive['destinos']['opengraph_image'] = 'http://www.hotel.com/img/logo.png';
$traduccionesArchive['destinos']['opengraph_image_size'] = 100;
$traduccionesArchive['ofertas']['title'] = 'Ofertas Hotel Costa del Sol, Costa de la Luz ';
$traduccionesArchive['ofertas']['metakey'] = 'palabra1, palabra2, palabra3';
$traduccionesArchive['ofertas']['metadesc'] = 'Ahorra en tus vacaciones con las ofertas en nuestros hoteles de la Costa del Sol, Costa de la Luz y Andalucia.';
$traduccionesArchive['ofertas']['opengraph_type'] = 'object';
$traduccionesArchive['ofertas']['opengraph_image'] = 'http://www.hotel.com/img/logo.png';
$traduccionesArchive['ofertas']['opengraph_image_size'] = 100;
But now, it not works, but in the past works fine, the filter is form module yoast SEO https://yoast.com/wordpress/plugins/seo/
Y tried with this Wordpress: How to return value when use add_filter?
I'm a little confused because this:
add_filter( 'wpseo_title', function(){return 'foo';}
Works outside the get_archive_seo functions, but not works inside function.
Can anybody help me?
You can use like this, this may help to you.
function title_function_name($title) {
$title = "Your title write here";
return $title;
}
add_filter('wp_title', 'title_function_name', 15);
if (!has_filter('wpseo_title'))
add_filter('wpseo_title', 'title_function_name', 15);
Hello community have a query, the issue is that I have a method that consulted the database, which invokes the method assume time parametrically.
As I commented'm using the PHP framework CodeIgniter, the question is this once consulted and loaded the first list of arrays, called: $listSubPrim
I want that list of arrays, add another array that is in the list $listSubSecu, but the issue is that I notice that does not work the way I want, although the method add array_push
principal_model.php
<?php
class Principal_model extends CI_Model {
public function __construct() {
$this->load->database();
}
function obtenerPermisosNivel($icodrol, $nivelmenu) {
try{
$sql = 'SELECT ICODMAEMENU, ICODROL, VDESMAEMENU, VDESICONO, VDESIDMAEMENU, ';
$sql = $sql.'ICODPADMENU, VDESCOMAND, SIORDPRIORIDAD, ICODSUBMENU, BACTIVO ';
$sql = $sql.'FROM TABMAEMENU ';
$sql = $sql.'WHERE ICODROL = ? ';
$sql = $sql.'AND BACTIVO = ? ';
switch ($nivelmenu) {
case NIVEL_SUB_MENU_PRIMARIO:
$sql = $sql.'AND ICODPADMENU IS NULL ';
$sql = $sql.'ORDER BY ICODMAEMENU ';
break;
case NIVEL_SUB_MENU_SECUNDARIO:
$sql = $sql.'AND ICODPADMENU IS NOT NULL ';
$sql = $sql.'AND ICODSUBMENU IS NULL ';
$sql = $sql.'ORDER BY SIORDPRIORIDAD ';
break;
case NIVEL_SUB_MENU_TERCIARIO:
$sql = $sql.'AND ICODPADMENU IS NOT NULL ';
$sql = $sql.'AND ICODSUBMENU IS NOT NULL ';
$sql = $sql.'ORDER BY SIORDPRIORIDAD ';
break;
}
$query = $this->db->query($sql, array($icodrol, ESTADO_ACTIVO));
return $query->result_array();
} catch(Exception $e){
log_message('debug', $e->getMessage()); // use codeigniters built in logging library
show_error($e->getMessage()); // or echo $e->getMessage()
}
}
function obtenerPermisosMenu($icodrol) {
try{
/* Obtenemos el listado de SubMenus Primarios de toda la lista */
$listSubPrim = $this->obtenerPermisosNivel($icodrol, NIVEL_SUB_MENU_PRIMARIO);
/* Obtenemos el listado de SubMenus Secundarios de toda la lista */
$listSubSecu = $this->obtenerPermisosNivel($icodrol, NIVEL_SUB_MENU_SECUNDARIO);
/* Obtenemos el listado de SubMenu de asociado al SubMenu primario */
foreach ($listSubPrim as $pri) {
$listSubMenuItem = array();
foreach ($listSubSecu as $sec) {
if($sec['ICODPADMENU'] == $pri['ICODMAEMENU']) {
array_push($listSubMenuItem, $sec);
}
}
if (count($listSubMenuItem) > 0) {
array_push($pri, $listSubMenuItem);
}
}
/* Obtenemos el listado de SubMenus Terciarios de toda la lista */
$listSubTerc = $this->obtenerPermisosNivel($icodrol, NIVEL_SUB_MENU_TERCIARIO);
/* Obtenemos el listado de SubMenu de asociado al SubMenu secundario */
foreach ($listSubPrim as $pri) {
$listSubSecu = $pri[10];
if (is_array(listSubSecu)) {
foreach (listSubSecu as $sec) {
$listSubMenuItem = array();
foreach ($listSubTerc as $ter) {
if($sec['ICODMAEMENU'] == $ter['ICODSUBMENU']) {
array_push($listSubMenuItem, $sec);
}
}
array_push($sec, $listSubMenuItem);
}
}
}
return $listSubPrim;
} catch(Exception $e){
log_message('debug', $e->getMessage()); // use codeigniters built in logging library
show_error($e->getMessage()); // or echo $e->getMessage()
}
}
}
?>
I realize that walking back on the list: $listSubPrim
Limited position 10 of the array should be an array, so as indicated in the code.
$listSubSecu = $pri[10];
I hope you have understood my question.
Basically I want just a list of fixes, with three levels.
Thank you.
Hello I will explain more clearly the impression the first list of arrays: $listSubPrim
$listSubPrim = $this->obtenerPermisosNivel($icodrol, NIVEL_SUB_MENU_PRIMARIO);
$listSubSecu = $this->obtenerPermisosNivel($icodrol, NIVEL_SUB_MENU_SECUNDARIO);
foreach ($listSubPrim as $pri) {
log_message('debug', '-> '.$pri['ICODMAEMENU'].' - '.$pri['ICODROL'].' - '.$pri['VDESMAEMENU']);
}
I printed the results of a list of arrays, as you will notice:
DEBUG - 2015-06-10 16:43:31 --> -> 85 - 2 - Las 20 Mejores Ofertas
DEBUG - 2015-06-10 16:43:31 --> -> 86 - 2 - Ofertas Inteligentes
DEBUG - 2015-06-10 16:43:31 --> -> 87 - 2 - Descuentos Restaurantes
DEBUG - 2015-06-10 16:43:31 --> -> 88 - 2 - Categorias
I need you in that row, add the list of array: $listSubSecu, for each row that is within the array foreach.
Aya hope I understood.
Thank you.
I want to insert 2 times but I have routes that redirects each other, I make the first Insertion and then redirijo to another path to insert again. Would have to put begin-> transanction ()
This well done ?. regards
I first made the first Insertion, in the route
$app->post("/orders/insert", function() use($app)
{
$empleado = ORM::for_table('empleado')->select('id')->where('usuario_idusuario',$_SESSION['user_id'])->find_one();
$cliente = 'proveedor';
if(!$empleado)
{
$app->flash('error','La cuenta de usuario tiene que estar asociado a un empleado registrado en la base de datos');
$app->redirect($app->urlFor('cartList'));
}
try
{
$insertOrder = ORM::for_table('pedido')->create();
$insertOrder->fechapedido = date('Y/m/d');
$insertOrder->estado = 1;
$insertOrder->empleado_id = $empleado->id;
$insertOrder->proveedor_id = $_SESSION['idproveedor'];
$insertOrder->save();
$app->redirect("/lineorder/insert/$cliente");
}
catch(PDOException $e)
{
$app->flash('error','Ha ocurrido un error en la base de datos, no se ha insertado ningún pedido'.$e->getMessage());
$app->redirect($app->urlFor('cartList'));
}
});
After I go to the route that redirect and realized:
$app->map('/lineorder/insert/:cliente', function($cliente) use($app)
{
if(!isset($_SESSION['cart-items']))
{
$app->redirect($app->urlFor('create-order'));
$app->flash('error','No tienes carritos');
}
//Si existe la variable de sesion
else
{
if(count($_SESSION['cart-items'])>0)
{
$idpedido = ORM::for_table('pedido')->count();
foreach($_SESSION['cart-items'] as $id => $cantidad)
{
$producto = ORM::for_table('producto')->select_many('id','precioVenta','precioProveedor')->where('id',$id)->find_one();
$preciounidad = ($cliente==='proveedor') ? $producto->precioProveedor : $producto->precioVenta;
$lineorder_insert = ORM::for_table('lineapedido')->create();
$lineorder_insert->pedido_idpedido = $idpedido;
$lineorder_insert->producto_idproducto =$producto->id;
$lineorder_insert->cantidad = $cantidad;
$lineorder_insert->preciounidad = $preciounidad;
$lineorder_insert->save();
//Actualizo cantidad en la table productos
$cantidad_stock =$producto->cantidad_stock;
$cantidad_stock+=$cantidad;
$update_amount = ORM::for_table('producto')->find_one($id);
$update_amount->set('cantidad_stock',$cantidad_stock);
$update_amount->save();
$app->flash('success',"pedido {$idpedido} creado correctamente");
$app->redirect($app->urlFor('orderList'));
}
}
}
})->via('GET','POST');
I need begin->transaction()
Would you be well done?