Passing multiple parameters via a url in MVC framework - php

I'm trying to pass multiple parameters in a url that looks like this...
http://somedomain.com/lessons/lessondetails/5/3
... to a function in the controller that looks like this ...
class LessonsController extends Controller
{
public function lessonDetails($studentId, $editRow=NULL)
{
try {
$studentData = new StudentsModel();
$student = $studentData->getStudentById((int)$studentId);
$lessons = $studentData->getLessonsByStudentId((int)$studentId);
if ($lessons)
{
$this->_view->set('lessons', $lessons);
}
else
{
$this->_view->set('noLessons', 'There are no lessons currently scheduled.');
}
$this->_view->set('title', $student['first_name']);
$this->_view->set('student', $student);
return $this->_view->output();
} catch (Exception $e) {
echo "Application error: " . $e->getMessage();
}
}
}
But only the first parameter seems to pass successfully.
Not sure what to copy and paste here but here's the bootstrap.php...
$controller = "students";
$action = "index";
$query = null;
if (isset($_GET['load']))
{
$params = array();
$params = explode("/", $_GET['load']);
$controller = ucwords($params[0]);
if (isset($params[1]) && !empty($params[1]))
{
$action = $params[1];
}
if (isset($params[2]) && !empty($params[2]))
{
$query = $params[2];
}
}
$modelName = $controller;
$controller .= 'Controller';
$load = new $controller($modelName, $action);
if (method_exists($load, $action))
{
$load->{$action}($query);
}
else
{
die('Invalid method. Please check the URL.');
}
Thanks in advance!

Call $this->getRequest()->getParams() from your action controller and check if both parameters are there.
If NO, the problem lies with your routing.
If YES, the problem lies with passing the parameters to your controller method lessonDetails.
Also, lessondetailsAction is missing. (this will be the method called if you visit the url you posted)

Related

Call Magic methods in Eloquent laravel 5.2

i try use __call magic method for make dynamic method in laravel Eloquent.
i have blog and blog_translations table and TITLE,CONTENT must be load from blog_translations table .
public function translations($lang = null)
{
if(empty($lang)) {
if (!empty(Lang::getLocale())) {
$language = Lang::getLocale();
} else {
$language = Config::get('app.fallback_locale');
}
}else{
$language = $lang;
}
return $this->hasMany(Blog_Translation::class)->where('locale', $language);
}
public function __call($method,$arg)
{
$filed = str_replace('get','',$method);
if(sizeof($arg) >= 1){
$lang = $arg[0];
}else {
$lang = '';
}
return $this->translations($lang)->where('name',$filed)->first()->text;
}
in controller :
$blog = Blog::find(1);
return $blog->getTITLE();
error :
Undefined property:
Illuminate\Database\Eloquent\Relations\HasMany::$id
with remove __call function relationship work good.

How to restrict user to change the URL in PHP

I would like to know that if there is a method in the controller which require arguments and the user changes the argument in the URL by hand, and presses enter it should display the default page. Below is my bootstrap, then I have already created a error controller for URL error. So please give some coding guide or if there is some thing in my code, change it. Thanks in advance.
<?php
class App
{
protected $controller = 'indexController';
protected $method = 'index';
protected $params = array();
public function __construct()
{
$url = $this->parseUrl();
//print_r($url);
if (isset($url[0]))
{
if (file_exists('app/controllers/'.$url[0].'.php'))
{
$this->controller = $url[0];
unset($url[0]);
}
require_once('app/controllers/'.$this->controller.'.php');
$this->controller = new $this->controller;
}
else
{
$error = new errorController();
$error->setError("Page Not Found");
echo $error->getError();
}
if (isset($url[1]))
{
if (method_exists($this->controller,$url[1]))
{
$this->method = $url[1];
unset($url[1]);
}
else
{
$error = new errorController();
$error->setError("Page Not Found");
echo $error->getError();
}
}
else
{
$error = new errorController();
$error->setError("Page Not Found");
echo $error->getError();
}
$this->params = $url ? array_values($url) : array();
call_user_func_array(array($this->controller,$this->method),$this->params);
}
public function parseUrl()
{
if (isset($_GET['url']))
{
return $url =explode('/',filter_var(rtrim($_GET['url'],'/'),FILTER_SANITIZE_URL));
}
}
}
The method itself must check if the parameters provided are valid and throw an exception if not. Afterwards just catch the exception and trigger and error page to be displayed.
Seems like you could use POST and $_POST, instead of GET. Then it won't matter if the user includes or alters parameters because your PHP will ignore them.

call to a member function describetable() on a non-object

I was trying one trick with the zendframework , I wanted to created a class that generate the dbTable automaticaly :
here is the class i defined :
class DbTable extends Zend_Db_Table_Abstract {
public $db_table;
public function __construct ($model_name='')
{
//echo "setting database";
$this->db_table = $this->get_db_table($model_name);
}
public function get_db_table($model_name='')
{
if(!empty($model_name))
{
$model = 'Application_Model_DbTable_'.ucfirst($model_name);
if (null === $this->db_table)
{
$this->set_db_table($model);
}
return $this->db_table;
}
else
{
throw new Exception('Database Table was not defined');
}
}
public function set_db_table($dbTable)
{
if (is_string($dbTable)) {
$dbTable = new $dbTable();
}
if (!$dbTable instanceof Zend_Db_Table_Abstract) {
throw new Exception('Invalid table data gateway provided');
}
return $this->db_table = $dbTable;
}
}
and when I try to use it on the for example the User model to find a user with it's id with the function i defined:
public function find_by_id($id=0)
{
$DbTable = new DbTable('User');
$result = $database->find($id);
if(empty($result))
{
return false;
}
else
{
$row = $result->current();
$entry = $this->instantiate($row);
return $entry;
}
}
i get the error mentioned above !
Any help ? thanks anyway !
I think you miss adapter.
Try this:
Replace
$DbTable = new DbTable('User');
$result = $database->find($id);
by
$DbTable = new DbTable('User');
$result = $DbTable->db_table->find($id);

calling statically and dynamically same method

i'm writing a php class that is like an orm.
I have a method, that can be called statically or instanciated, and it must work in both cases.
Can you see what's wrong.
Basically is an object called Model.
When created it creates a table based on the inherited class.
For example:
Podcast extends Model ....
There are some functions like this that needs to be called statically and dynamically.
for example:
$podcastList = Podcast::findAll($db);
I get all podcasts objects from DB without need to have a podcast object instanciated.
But i can also do:
$podcast = new Podcast($db)
$podcastList = $podcast->findAll(); //no db here.... passed before
$db is a class i wrote to make operation on Database. IT simply does with OOP, what mysql_* do with functions. I'm not using PDO, i may use in future, but now i use mysql_* :P
that are the incriminated functions
public static function findAll($db=NULL, $self=NULL) {
if($self == NULL) {
$self = new static($db);
} else {
$self = $this;
}
$self->tableName = "";
$self->db = NULL;
$is_static = !(isset($this) && get_class($this) == __CLASS__);
if($is_static) {
//die(__CLASS__ . "::" . __FUNCTION__ . " CALLED STATICALLY");
if(!$self->db) {
die(__CLASS__ . "::" . __FUNCTION__ . " CALLED STATICALLY AND DB IS NULL");
//It stops here!
}
$self->tableName = $self->genTableName();
} else {
$self->db = $this->db;
$self->tableName = $this->tableName;
}
$query = "SELECT * FROM {$self->tableName}";
$r = $self->db->exec($query);
if(!$r) {
die(__CLASS__ . ":Error " . __FUNCTION__ . " record: " . $self->db->getError());
}
if($self->db->countRows($r) == 0) {
return NULL;
}
$objects = array();
while($row = $self->db->fetch($r, DBF::FETCH_ASSOC)) {
$objectClass = __CLASS__;
$object = new $objectClass($this->db);
//TODO Do it dinamically indipendently of column name
$f = get_class_vars($objectClass);
foreach ($f as $field => $value) {
$chuncks = explode("_", $field);
if($chuncks[0] == "f") {
$object->{$field} = $row[$chuncks[2]];
}
}
$objects[] = $object;
}
return $objects;
}
public function __call($name, $arguments) {
if ($name === 'findAll'){
return static::findAll($arguments, $this);
}
}
Both are part of a class.
Thank you for the help !
There's a lot wrong with this code. More important than your many logic mistakes (why are you setting $self = $this, then $self->db = NULL, then $self->db = $this->db?) is that you are misunderstanding what it means to be able to call static functions dynamically in PHP. The object $this simply doesn't exist in a static method. The call $podcast->findAll() looks non-static, but it's still static.
To do what you want to do, here are some options:
leave the function static and call findAll($this->db, $tablename) as needed
put the function into the db class and call it with parameter tablename
EDIT:
The second in my list is how I would do it. This is because you already have to have a db object in your original example, and there is nothing in particular that makes the function's purpose only suited to Podcast objects and not to, say, any other object representing database rows.
//calling examples:
$podcastlist = $db->findAll('Podcast');
$podcast = new Podcast($db);
$podcastlist = $podcast->findAll();
public class db {
....
function findAll($classname, $tablename=NULL) {
if(!isset($tablename)) {
//let's pretend you put default table names as class constants
$tablename = get_constant($classname.'::DEFAULT_TABLE');
}
$query = "SELECT * FROM {$tableName}";
$r = $this->exec($query);
if(!$r) {
throw new Exception("Error " . __FUNCTION__ . " record: " . $this->getError());
}
if($this->countRows($r) == 0) {
return NULL;
}
$objects = array();
while($row = $this->fetch($r, DBF::FETCH_ASSOC)) {
$object = new $classname($this);
//the following is an easier way to do your original foreach
foreach($row as $field=>$value) {
if(property_exists($classname, "f_".$field)) {
$object->{'f_'.$field} = $value;
}
}
$objects[] = $object;
}
//something you forgot:
return $objects;
}
}
public class Podcast extends Model {
....
public function findAll($tablename=NULL) {
return $this->db->findAll(class_name($this), $tablename);
}
}

_forward() in Zend does not work?

Here is a code:
public function loginAction()
{
$form = new Application_Form_Login();
$this->view->form = $form;
if($this->_request->isPost())
{
self::$dataForm = $this->_request->getPost();
if($this->form->isValid(self::$dataForm))
{
return $this->_forward('authorization');
} else
{
$this->form->populate(self::$form);
}
}
}
public function authorizationAction()
{
if($this->_request->isPost())
{
$auth = Zend_Auth::getInstance();
$authAdapter = new Application_Model_User($this->user->getAdapter(),'user');
$authAdapter->setIdentityColumn('USERNAME')
->setCredentialColumn('PASSWORD');
$password = md5(self::$dataForm['password']);
$authAdapter->setIdentity(self::$dataForm['username']);
$authAdapter->setCredental($password);
$result = $auth->authenticate($authAdapter);
echo 'ok';
/*
if($result->isValid())
{
//$this->_forward('authorized', 'user');
echo 'ok';
}*/
}
}
Any idea why it does not work? I didn't get any error just blank page.
Shouldn't you be calling if($form->isValid(self::$dataForm)) ?
As far as I understand it is a bad idea to use the $this->_forward() as it calls the dispatch loop again.
Personally I would place the authorization code into a model class and pass it the username & password from the form.

Categories