Creating multilanguage homepage - php

so im making homepage with three languages.
I am using switch method, here is code -
public function languages()
{
if (isset($_GET['lang']) && $_GET['lang'] != '')
{
$_SESSION['lang'] = $_GET['lang'];
}
else
{
$_SESSION['lang'] = 'en_EN';
}
switch($_SESSION['lang'])
{
case 'en_EN': require_once('language/lang.eng.php');break;
case 'lv_LV': require_once('language/lang.lv.php');break;
case 'ru_RU': require_once('language/lang.ru.php');break;
default: require_once('language/lang.eng.php');
}
}
public function translate($txt)
{
global $text;
return $text[$txt];
}
and it should display in index.php file like this -
<?php $index->translate('search'); ?>
but the problem is that it shows no errors, no notices, no warnings and no translated or default text.
I included function languages() , maybe you can help me with this problem?
EDIT:
im calling $language at start of index.php file - <?php require_once('class.index.php'); $index = new index; $index->languages(); ?> and $text is defined in lang.eng.php; lang.lv.php and lang.ru.php file.

Since you're using a class, I think it's better to use properties instead of globals, it will be easier in future mantainance. Create a class variable holding $text and use that
class Index {
var $text;
public function languages()
{
require(".....");
$this->text = $text;
}
public function translate($txt)
{
if(isset($this->text[$txt]))
{
return $this->text[$txt];
}
else
{
return "no translation";
}
}
}
$index = new Index;
$index->languages();
echo $index->translate('search');

type
<?php echo $index->translate('search'); ?>

Check first whether the session is initialized or not and also place the languages() function call before the translate so that it loads the language prior to translation and also put error_reporting(E_ALL) at top so that any error suppresion will be be removed and also put echo the returned result of translate statement

Related

How to check if constant is defined, inside function - php

I am trying to make a small PHP function which can check if a constant is defined, and if so, echo it, and if not, echo space or nothing.
Right now, the if(defined() part is not working, because the constant is being transferred to a variable inside the function.
function getConstant($constant) {
if(defined($constant)) {
echo constant($constant);
} else {
echo '';
}
}
The echo constant($constant) part is working fine, but I cannot check if the constant is actually defined because it is a variable now.
I cannot seem to find a solution for it
public static function isConstants($constant) {
$oClass = new ReflectionClass(__CLASS__);
$allConstants = $oClass->getConstants();
if (isset($allConstants[$constant])) {
echo $allConstants[$constant];
} else {
echo '';
}
}

Cookie check in OOP

Until yesterday I was burning my brain trying to switch from a procedural thinking to a OOP thinking; this morning I gave up. I said to my self I wasn't probably ready yet to understand it.
I started then coding in the usual way, writing a function to check if there's the cookie "logged" or not
function chkCookieLogin() {
if(isset($_COOKIE["logged"])) {
$logged = 'true';
$cookieValue = $_COOKIE["logged"];
return $logged;
return $cookieValue;
}
else {
$logged = 'false';
return $logged;
}
}
$result = chkCookieLogin();
if($result == 'true'){
echo $cookieValue;
}
else {
echo 'NO COOKIE';
}
since I run across a problem: I wanted to return two variables ($logged and $cookieValue) instead of just one. I google it and I found this answer where Jasper explains a method using an OOP point of view (or this is what I can see).
That answer opened me a new vision on the OOP so I tried to rewrite what I was trying to achieve this way:
class chkCookie {
public $logged;
public $cookieValue;
public function __construct($logged, $cookieValue) {
$this->logged = $logged;
$this->cookieValue = $cookieValue;
}
function chkCookieLogin() {
$out = new chkCookie();
if(isset($_COOKIE["logged"])) {
$out->logged = 'true';
$out->cookieValue = $_COOKIE["logged"];
return $out;
}
else {
$out->logged = 'false';
return $out;
}
}
}
$vars = chkCookieLogin();
$logged = $vars->logged;
$cookieValue = $vars->cookieValue;
echo $logged; echo $cookieValue;
Obviously it didn't work at the first attempt...and neither at the second and the third. But for the first time I feel I'm at one step to "really touch" the OOP (or this is what I think!).
My questions are:
is this attempt correctly written from the OOP point of view?
If yes, what are the problems? ('cause I guess there's more than one)
Thank you so much!
Credit to #NiettheDarkAbsol for the idea of returning an Array data-type.
Using dependency injection, you can set-up an object like this:
class Factory {
private $Data = [];
public function set($index, $data) {
$this->Data[$index] = $data;
}
public function get($index) {
return $this->Data[$index];
}
}
Then to use the DI module, you can set methods like so (using anonymous functions):
$f = new Factory();
$f->set('Cookies', $_SESSION);
$f->set('Check-Cookie', function() use ($f) {
return $f->get('Cookies')['logged'] ? [true, $f->get('Cookies')['logged']] : [false, null];
});
Using error checks, we can then call the method when and as we need it:
$cookieArr = is_callable($f->get('Check-Cookie')) ? call_user_func($f->get('Check-Cookie')) : [];
echo $cookieArr[0] ? $cookieArr[1] : 'Logged is not set';
I'd also consider adding constants to your DI class, allowing more dynamic approaches rather than doing error checks each time. IE, on set() include a constant like Factory::FUNC_ARRAY so your get() method can return the closure already executed.
You can look into using ternary operators if you're confused.
See it working over at 3v4l.org.
If it means anything, here is an OOP styled approach.

PHP Vars From Included Bootstrap Not Showing Up in View

I have created my own little PHP framework for fun, however, I am having trouble passing variables from bootstrap to the views....
if I put an echo,print_r,var_dump my target variable in the bootstrap, the output is displayed in the browser before the tag... yet the target var in bootstrap.php is not available in the view, it is coming up as "" even though at the top of the page it is being output correctly....
Somethings I noticed from similar questions:
- The target variable is not being over written
- The include target path is correct and the file exists
- The file is only being included one time (include_once is only fired once)
Any ideas are greatly appreciated, I am pulling my hair out over here lol...
Source Code
https://gist.github.com/jeffreyroberts/f330ad4a164adda221aa
If you just want to display your site name, I think you can use a constant like that :
define('SITE_NAME', "Jeff's Site");
And then display it in your index.tpl :
<?php echo SITE_NAME; ?>
Or, you can send your variables to the view by extending a little bit your JLR_Core_Views :
class JLR_Core_Views
{
private $data;
public function loadView($templatePath, $data = array())
{
$this->data = $data;
$templatePath = JLR_ROOT . '/webroot/' . $templateName . '.tpl';
if(file_exists($templatePath)) {
// Yes, I know about the vuln here, this is just an example;
ob_start();
include_once $templatePath;
return ob_get_clean();
}
}
function __get($name)
{
return (isset($this->data[$name]))
? $this->data[$name]
: null;
}
}
Then, you can call your template like that :
$view = new JLR_Core_Views();
$view->loadView("index", array("sitename" => "Jeff's Site"));
And here is your index.tpl :
<?php echo $this->siteName; ?>
Below is another example of what you can do.
First, you create this class in order to store all the variables you want :
<?php
class JLR_Repository {
private static $data = array();
public function set($name, $value) {
self::$data[$name] = $value;
}
public function get($name) {
return (isset(self::$data[$name]))
? self::$data[$name]
: null;
}
}
?>
Then, when you want to store something in it :
JLR_Repository::set("sitename", "Jeff's Site");
And in your index.tpl :
<?php echo JLR_Repository::get("sitename"); ?>
try using the 'global' keyword - http://php.net/manual/en/language.variables.scope.php

PHP Query string for templating using if and isset()

I'm currently organising my site by forcing everything through index.php using .htaccess. Then I'm including some logic that uses the $REQUEST_URI to display the relevant template (see the code). My problem is that I find it annoying to have to check the the request array value is set every single time, eg if (isset($request[1])&&$request[1]=="projects"){...
Is there a way that I can just write if ($request[1]=="projects"){...
The above line, throws an error if $request[1] is not set, ie on the home page.
Here's my complete code. It shows an individual project on mydomain.com/projects/house,
and it shows a list of projects on mydomain.com/projects
$request = explode("/", $_SERVER['REQUEST_URI']);
if (isset($request[1])&&$request[1]=="projects"){
require("./controller/projects.php");
if (isset($request[2])){
include("./view/project.html");
} else {
include("./view/project-list.html");
}
Make a function!
function current_controller() {
if(isset($request[1])
return $request[1];
}
if(current_controller() === "projects") { ... }
Or you can do
function is_current_controller($controller) {
if(isset($request[1])&&$request[1] === $controller)
return true;
return false;
}
if(is_current_controller("projects") { ... }
Why not ditch the else/elseif method as use swtich()?
Like this
$request = explode("/", $_SERVER['REQUEST_URI']);
$check = $request[];
switch($check) {
case "1";
include (folder/file1.php);
break;
case "2";
include (folder/file2.php);
break;
case "3";
include (folder/file3.php);
break;
}

Are these underscored PHP functioned ever called?

Inherited an old CakePHP site and I'm trying to figure out what some functions do. I have several functions that have the same name as another function but with an underscore first, e.g. save() and _save(). However the function _save() is never called in any context, though save() is.
I read this question and it looks like it's from an old worst-practices exercise, but that doesn't really explain why it's in my code; you still have to call function _save() as _save() right? If there's no calls to _save() is it safe to remove?
I want it gone, even the save() function wasn't supposed to be there, rewriting perfectly good framework functionality. It looks like an older version of the same function, but there's no comments and I don't know if there's some weird context in which php/Cake will fall back to the underscored function name.
Here's the code for the curious. On closer inspection it appears the underscored functions were old versions of a function left in for some reason. At least one was a "private" method being called (from a public function of the same name, minus the underscore...):
function __save() {
$user = $this->redirectWithoutPermission('product.manage','/',true);
if ($this->data) {
$this->Prod->data = $this->data;
$saved_okay = false;
if ($this->Prod->validates()) {
if ($this->Prod->save()) $saved_okay = true;
}
if ($saved_okay) {
$product_id = ($this->data['Prod']['id']) ? $this->data['Prod']['id'] : $this->Prod->getLastInsertId();
if ($this->data['Plant']['id']) {
$this->data['Prod']['id'] = $product_id;
$this->Prod->data = $this->data;
$this->Prod->save_plants();
$this->redirect('/plant/products/'.$this->data['Plant']['id']);
} else {
$this->redirect('/product/view/'.$product_id);
}
die();
} else {
die('did not save properly');
}
} else {
die('whoops');
}
}
function save() {
$user = $this->redirectWithoutPermission('product.manage','/products',true);
if ($this->data) {
$this->Prod->data = $this->data;
if ($this->Prod->validates()) {
$this->Prod->save();
$gotoURL = isset($this->data['Navigation']['goto'])?$this->data['Navigation']['goto']:'/';
$gotoURL = str_replace('%%Prod.id%%', $this->data['Prod']['id'], $gotoURL);
if (isset($this->data['Navigation']['flash'])) {
$this->Session->setFlash($this->data['Navigation']['flash']);
}
if (isset($this->params['url']['ext']) && $this->params['url']['ext']=='ajax') {
$value = array(
'success'=>true
,'redirect'=>$gotoURL
);
print $this->Json->encode($value);
} else {
$this->redirect($gotoURL);
}
} else {
$value = array(
'success'=>false
,'message'=>"You have invalid fields."
,'reason'=>'invalid_fields'
,'fields'=>array(
'Prod'=>$this->Prod->invalidFields()
)
);
print $this->Json->encode($value);
}
} else {
$this->redirect('/products');
}
die();
}
I had hoped to learn whether or not some convention applied to this situation, but from testing I've found the functions are not called which is really the answer to the question I asked.

Categories