Passing property to PHP method - php

I have the following class, where I added the property $user.
include_once(__CA_LIB_DIR__."/ca/Search/BaseSearch.php");
include_once(__CA_LIB_DIR__."/ca/Search/ObjectSearchResult.php");
class ObjectSearch extends BaseSearch {
# ----------------------------------------------------------------------
/**
* Which table does this class represent?
*/
protected $ops_tablename = "ca_objects";
protected $ops_primary_key = "object_id";
public $user;
# ----------------------------------------------------------------------
public function &search($ps_search, $pa_options=null, $user) {
return parent::doSearch($ps_search, new ObjectSearchResult(), $pa_options);
}
# ----------------------------------------------------------------------
}
?>
In the following code I can't pass the $user property to the search method. I tried with $user, $this->user and new ObjectSearch($user). Being new to PHP I know I'm asking a naive question, but I can't solve it by myself, believe me I tried for days. How can I accomplish this?
$po_request = $this->getVar('request');
$vs_widget_id = $this->getVar('widget_id');
$user = $this->getVar('user');
$o_search = new ObjectSearch();
$result = $o_search->search('created.$user.:"2013"');
$count = 1;
while($result->nextHit()) {
print "Hit ".$count.": "."<br/>\n";
print "Idno: ".$result->get('ca_objects.idno')."<br/>\n";
print "Name: ".$result->get('ca_objects.preferred_labels.name')."<br/>\n";
$count++;
}
?>

public function &search($ps_search, $pa_options=null, $user)
There are a few things wrong with it:
It doesn't make any sense to pass a parameter without default value after a parameter which has a default value
You have to pass the third parameter here (you only pass one)
You don't have to pass the class properties manually; they're automatically in $this
So write:
public function &search($ps_search, $pa_options=null) {
return parent::doSearch($ps_search, new ObjectSearchResult($this->user), $pa_options);
}
Or where ever you may need your $user class property, write simply $this->user.
$this is always set in object context: you don't need to pass it yourself.

Don't confuse double quotes with single ones. You have to either use concatenation or double ones here:
$result = $o_search->search('created ' . $user . ': 2013');
or
$result = $o_search->search("created $user: 2013");

Related

Undefined index error when trying to echo values, I am using functions outside of the class

Hey guys I have a question and I still consider myself pretty new at coding, so forgive me if I come off foolish.
I am studying in school as of now and we have a project to build a full stack recreation of craigslist. Any who the problem I am having deals with PHP. I have created an account page with text areas. I would like to echo out the user's information on their so the user can see what he put on and update as he likes. Since my navbar is included on every page, I added the code:
if(isset($_SESSION['logged_in_user'])){
var_dump($_SESSION['logged_in_user']);
$user = $_SESSION['logged_in_user'];
var_dump($user);
}
on my account page I figured I can echo it out as
<?= $attributes['first_name']?> within the placeholders. But I keep getting:
Undefined index: first_name
Also when I var_dump($user) I get an protected $attributes array.
In My Auth class is where I first defined $user as such:
public static function attempt($attemptedUsername, $attemptedPassword) {
$user = User::findByUserName($attemptedUsername);
if ($user == null) {
return false;
}
$validPassword = password_verify($attemptedPassword,$user->password);
if ($validPassword == true) {
$_SESSION['logged_in_user'] = $user;
}
return false;
}
and my findByUserName function is in the user class. the code is:
public static function findByUserName($user_name){
// Get connection to the database
self::dbConnect();
$stmt = self::$dbc->prepare('SELECT * FROM users WHERE user_name = :user_name');
$stmt->bindValue(':user_name', $user_name , PDO::PARAM_STR);
//execute gets its own line, t or false
$stmt->execute();
$result=$stmt->fetch(PDO::FETCH_ASSOC);
// #TODO: Create select statement using prepared statements
// #TODO: Store the result in a variable named $result
// The following code will set the attributes on the calling object based on the result variable's contents
$instance = null;
if ($result) {
$instance = new static($result);
}
return $instance;
}
Your problem seems to be with not being able to access the variable $user outside of the static method attempt() this can be fixed by declaring the variable globally at the beginning of the method attempt() like this:
public static function attempt($attemptedUsername, $attemptedPassword) {
global $user;
$user = User::findByUserName($attemptedUsername);
if ($user == null) {
return false;
}
$validPassword = password_verify($attemptedPassword,$user->password);
if ($validPassword == true) {
$_SESSION['logged_in_user'] = $user;
}
return false;
}
More information can be found on this in the PHP documentation here.

ZF2 Between Dates

I've been unable to successfully retrieve records between two dates in Zend Framework 2.
My code looks as follows:
$select = $this->getTimeTable();
$predicate = new \Zend\Db\Sql\Where();
$select->where($predicate->between("start_date", $week_sunday_date , $satruday_date));
public function getTimeTable()
{
if (!$this->timeTable)
{
$this->timeTable = new TableGateway(
'time',
$this->getServiceLocator()->get('Zend\Db\Adapter\Adapter')
);
}
return $this->timeTable;
}
"start_date" is the column in my DB that is of type DATETIME, and $week_sunday_date , $satruday_date are both generated as follows
$week_sunday_date = date("Y-m-d\TH:i:sP",strtotime('this sunday'));
$satruday_date = date("Y-m-d\TH:i:sP",strtotime("+6 day", strtotime($week_sunday_date)));
The database connection is good and I can otherwise get data. Dumping both $week_sunday_date and $satruday_date variables above I see:
string(25) "2014-11-08T00:00:00+00:00"
string(25) "2014-11-02T00:00:00+00:00"
I've also tried several other ways of in between but ultimately the page is blank and won't load due to an error.
Seems like I need something like this:
$statement = $sql->prepareStatementForSqlObject($select);
$time_list = $statement->execute();
But not sure how to initialize $sql properly.
I think the correct syntax would be:
$select->where->between('start_date', $week_sunday_date, $saturday_date);
Oh, but since, in your case $select is an instance of TableGateway, then you probably need $select->getSql()->where->between(...).
I'm a little rusty on TableGateway, we've strayed away from using it. But I think you can do something like:
$timeTable = new TableGateway(/*...*/);
$select = $timeTable->getSql()->select();
$select->columns(array('col1', 'col2'));
$select->where->between('start_date', $week_sunday_date, $saturday_date);
$resultSet = $timeTable->selectWith($select);
var_dump($resultSet->toArray());
Note: I do not recommend always converting the result set to an array, but it's nice to be able to do this for debugging purposes.
Example not using TableGateway:
Query class:
namespace Example\Model\Sql\Select;
use Zend\Db\Sql\Select;
class Time extends Select {
public function __construct($week_sunday_date, $saturday_date) {
parent::__construct(['t' => 'Time']);
$this->columns([
'col1',
'col2',
]);
$this->where->between('start_date', $week_sunday_date, $saturday_date);
}
}
Data model: (basically a glorified array object, just holds data, no business logic)
namespace Example\Model\DataContainer;
class Time extends \ArrayObject {
protected $col1;
protected $col2;
public function exchangeArray($data) {
$this->col1 = $data['col1'];
$this->col2 = $data['col2'];
}
public function getCol1() {
return $col1;
}
public function getCol2() {
return $col2;
}
}
Controller:
namespace Example\Controller;
use Example\Model\DataContainer;
use Example\Model\Sql\Select;
use Zend\Db\ResultSet\ResultSet;
class IndexController {
public function myExampleAction() {
$request = $this->getRequest();
$sm = $this->getServiceLocator();
$query = new Select\Time($request->getQuery('sunday'), $request->getQuery('saturday'));
$resultSet = new ResultSet(ResultSet::TYPE_ARRAYOBJECT, new DataContainer\Time());
$executer = $sm->get('Executer');
$resultSet = $executer->execute($query, $resultSet);
return [
'time' => $resultSet, // loop through results in your view
];
}
}
So, we create an instance of our query class, which is set up when you call the constructor implicitly by creating a new instance of it. We pass our parameters into it. Then, we create an instance of our result set class, and we specify the array object prototype. Each row returned by our query will be populated as an instance of the array object prototype. When the result set is initialized, it will automatically call exchangeArray() with the data returned for the current row. That method populates your data container, and so the result set is populated with an array of these populated data container objects. So when you loop through the result set, each row will be represented by an instance of your array object prototype.
You will have to define your own Executer class. That's not a built-in. You will have to create it and add it to the service config, so that you can get it out of the service manager like I've done in the example.
A quick example for the $sql property as you requested at the end of your question.
You should use:
use Zend\Db\Sql\Sql;
use Zend\Db\Sql\Select;
$adapter = $this->tableGateway->getAdapter();//get connection
$sql = new Sql($adapter);
$select = $sql->select();
$select->from($this->tableGateway->getTable())->where(array('active' => '1'));
$selectString = $sql->getSqlStringForSqlObject($select);
//echo $selectString;die;//this will show the quesry string build above.
$results = $adapter->query($selectString, $adapter::QUERY_MODE_EXECUTE);
$resultSet = new ResultSet();
$resultSet->initialize($results);
return $resultSet->toArray();//return array(use $resultSet->current() for one row)
i hope this helps

Creating default object from empty value (adding an item to a database for a new user in Laravel)

I have a function I am using to add
I have an array $data that contains the user data I am trying to put into the db. Everything works except for the "makeUrlTag" function portion:
public function makeUrlTag() {
$url_tag = '';
if(isset($this->data['user']['first_name'])) {
$url_tag = $url_tag . $this->data['user']['first_name'];
}
if(isset($this->data['user']['last_name'])) {
$url_tag = $url_tag.$this->data['user']['last_name'];
}
$fan->url_tag = $url_tag;
}
public function createFan() {
$fan = new Fan;
$fan->fbid = isset($this->data['user']['id']) ? $this->data['user']['id'] : '';
$fan->email = isset($this->data['user']['email']) ? $this->data['user']['email'] : '';
$fan->first_name = isset($this->data['user']['first_name']) ? $this->data['user']['first_name'] : '';
$fan->last_name = isset($this->data['user']['last_name']) ? $this->data['user']['last_name'] : '';
$this->makeUrlTag();
$fan->save();
}
I call createFan with:
$this->createFan();
When I run this, I get the error:
Creating default object from empty value
in reference to the makeUrlTag(); portion. Particularly the line:
$fan->url_tag = $url_tag;
Any idea what's going on here? Again, taking out the makeUrlTag portion works fine. Thank you.
It's because your makeUrlTag() method doesn't know about the Fan which is in the $fan variable you created in the createFan() method and trying to use a non-existing object in the scope of makeUrlTag() method using this:
$fan->url_tag = $url_tag;
So, you need to make your $fan object available to makeUrlTag() and to do this you may add a protected property in your class:
class YourClass {
protected $fan = null;
public function makeUrlTag(){
$url_tag = '';
// ...
$this->fan->url_tag = $url_tag;
}
public function makeUrlTag(){
$this->fan = new Fan;
// rest of your code
// but use $this->fan instead of $fan
$this->fan->save();
}
}
So, now you can access the $fan object from any method of your class ussing $this->fan, that's it.

Warning: Missing Argument 1

I am having some problems with my php code: All information returns but I cannot figure out why I am getting the error. For my index page I only inluded the line of code that is actually using that class there really is no other code other than some includes. Im sure it is how I built my __contstruct but i am not sure of the approriate way of doing it. I am missing something in how it is being called from the index page.
This line of code for my __construct works w/o error but I do not want the variable assigned in my class.
public function __construct(){
$this->user_id = '235454';
$this->user_type = 'Full Time Employee';
}
This is my Class
<?php
class User
{
protected $user_id;
protected $user_type;
protected $name;
public $first_name;
public $last_name;
public $email_address;
public function __construct($user_id){
$this->user_id = $user_id;
$this->user_type = 'Full Time Employee';
}
public function __set($name, $value){
$this->$name = $value;
}
public function __get($name){
return $this->$name;
}
public function __destroy(){
}
}
?>
This is my code from my index page:
<?php
ini_set('display_errors', 'On');
error_reporting(E_ALL);
$employee_id = new User(2365);
$employee_type = new User();
echo 'Your employee ID is ' . '"' .$employee_id->user_id. '"' . ' your employement status is a n ' . '"' .$employee_type->user_type. '"';
echo '<br/>';
?>
The problem is:
$employee_type = new User();
the constructor expect one argument, but you send nothing.
Change
public function __construct($user_id) {
to
public function __construct($user_id = '') {
See the outputs
$employee_id = new User(2365);
echo $employee_id->user_id; // Output: 2365
echo $employee_id->user_type; // Output: Full Time Employee
$employee_type = new User();
echo $employee_type->user_id; // Output nothing
echo $employee_type->user_type; // Output: Full Time Employee
If you have one user, you can do this:
$employer = new User(2365);
$employer->user_type = 'A user type';
echo 'Your employee ID is "' . $employer->user_id . '" your employement status is "' . $employer->user_type . '"';
Which output:
Your employee ID is "2365" your employement status is "A user type"
I'm no PHP expert, but it looks like you are creating 2 new instances of class user, and on the second instatiation, you are not passing the user_id into the constructor:
$employee_id = new User(2365);
This, it would seem to me, is creating a new instance of User and assigning this instance to the variable $employee_id - I don't think this is what you want though?
$employee_type = new User();
This looks like you're instantiating another instance of User and assigning it to variable $employee_type - but you have called the constructor User() without passing in an ID as is required - hence the error (missing argument).
The reason your return script contents look OK is because the first instance of the User class has an ID (because you passed it in) and the second one has an employee type because this is set in the constructor.
Like I say, I don't know PHP but I'm guessing you want something more along the lines of:
$new_user = new User(2365);
echo 'Your employee ID is ' . '"' .$new_user->user_id. '"' . ' your employement status is a n ' . '"' .$new_user->employee_type. '"';
Here, you are instantiating a single instance of your user class assigned to the variable $new_user, and then accessing the properties of that single instance.
EDIT: .....Aaaaaaaaand - I was too slow :-)

PHP getter method question

Hi Im new to PHP so forgive the basic nature of this question.
I have a class: "CustomerInfo.php" which Im including in another class. Then I am trying to set a variable of CustomerInfo object with the defined setter method and Im trying to echo that variable using the getter method. Problem is the getter is not working. But if I directly access the variable I can echo the value. Im confused....
<?php
class CustomerInfo
{
public $cust_AptNum;
public function _construct()
{
echo"Creating new CustomerInfo instance<br/>";
$this->cust_AptNum = "";
}
public function setAptNum($apt_num)
{
$this->cust_AptNum = $apt_num;
}
public function getAptNum()
{
return $this->cust_AptNum;
}
}
?>
<?php
include ('CustomerInfo.php');
$CustomerInfoObj = new CustomerInfo();
$CustomerInfoObj->setAptNum("22");
//The line below doesn't output anything
echo "CustomerAptNo = $CustomerInfoObj->getAptNum()<br/>";
//This line outputs the value that was set
echo "CustomerAptNo = $CustomerInfoObj->cust_AptNum<br/>";
?>
Try
echo 'CustomerAptNo = ' . $CustomerInfoObj->getAptNum() . '<br/>';
Or you will need to place the method call with in a "Complex (curly) syntax"
echo "CustomerAptNo = {$CustomerInfoObj->getAptNum()} <br/>";
As your calling a method, not a variable with in double quotes.
for concat string and variables, you can use sprintf method for better perfomace of you app
instead of this:
echo "CustomerAptNo = $CustomerInfoObj->getAptNum()<br/>";
do this:
echo sprintf("CustomerAptNo = %s <br />", $CustomerInfoObj->getAptNum());
check http://php.net/sprintf for more details

Categories