class News extends BaseNews
{
public function save(Doctrine_Connection $conn = null)
{
$this->setUserId($this->getAttribute('user_id'));
return parent::save($conn);
}
}
How can i get here current save News ID? I would like add this for session, but i dont know how can i get this?
Never used symfony but as far as I understand you, you want something like this:
class News extends BaseNews
{
public function save(Doctrine_Connection $conn = null)
{
$this->setUserId($this->getAttribute('user_id'));
$result = parent::save($conn);
echo $this->getId(); // Your news Id
return $result;
}
}
Related
How can we create member functions in php that can be called similarly to the way laravel does?
ex:
User::with('package')->where('id', $user_id)->get();
i tried creating a static function with a member function inside:
public static function getAll() {
public function withJoin($join_table, $local_key, $foreign_key) {
global $wpdb;
$table_name = $wpdb->prefix.'qre_events';
$query = "SELECT * from $table_name INNER JOIN $join_table ON $local_key = $foreign_key";
try {
$results = $wpdb->get_results($query);
} catch(Throwable $e) {
$results = null;
echo($e);
echo "Error retrieving data.";
}
var_dump($results);
}
global $wpdb;
$table_name = $wpdb->prefix. static::$table_name;
$query = "SELECT * from $table_name";
try {
$results = static::convertArrayToModelArray($wpdb->get_results($query),
static::$attributes);
} catch(Throwable $e) {
$results = null;
echo($e);
echo "Error retrieving data.";
}
return $results;
}
and tried calling it like so:
$results = Event::getAll()->withJoin($user_table, 'user_id', 'ID');
but it returned this error:
Fatal error: Uncaught Error: Call to a member function withJoin() on array
The method chaining is archived by returning $this for each method.
Like this:
class Event
{
public function getAll()
{
// Do stuff
return $this;
}
public function withJoin()
{
// Do stuff
return $this;
}
}
Now they can be called like this:
(new Event)->getAll()->withJoin();
So you have to save you parameters to properties on the class.
You can take a look inside Laravel builder to see exactly how it was archived there: https://github.com/laravel/framework/blob/6.x/src/Illuminate/Database/Eloquent/Builder.php
Try .
$results = Event::withJoin($user_table, 'user_id', 'ID')->get();
The chaining of methods works because each function returns an instance of an object that has functions on it.
// This
User::with('package')->where('id', $user_id)->get();
// Is basicly the same as
$user_query = User::with('package');
$user = $user_query->where('id', $user_id)->get();
You need to create two objects and the static function will return an instance of the other object. If you want method chaining as well, you just need to make sure that chainable functions return their own instance.
For example
class Event
{
public static function getAll()
{
return new EventObject();
}
}
class EventObject
{
public function withJoin()
{
// Do stuff here.
// return `$this` if you want to chain functions.
}
}
In this example, using Event::getAll() will give you an EventObject instance on which you can call the withJoin function. So you can now do the following:
Event::getAll()->withJoin();
Based on Alvin Bunk article link to article I want to create a web-cralwer that logins in a website then submits a form.
My problem is that on that website there is an Ajax block that generates after clicking and empty link few inputs that I need to fill so I need to click that empty link somehow or to insert the inputs manually .
I changed the code below in a lot of ways to try to make it work but on the visit function I got stuck
I get Uncaught Error: Call to a member function visit() on null
<?php
require 'vendor/autoload.php';
trait MinkSetup
{
private $minkBaseUrl;
private $minkSession;
/**
* #before
*/
public function setupMinkSession()
{
$this->minkBaseUrl = 'https://www.url.com';
$driver = new \Behat\Mink\Driver\Selenium2Driver('firefox');
$this->minkSession = new \Behat\Mink\Session($driver);
$this->minkSession->start();
}
public function getCurrentPage()
{
return $this->minkSession->getPage();
}
public function getCurrentPageContent()
{
return $this->getCurrentPage()->getContent();
}
public function visit($url)
{
echo $url;
$this->minkSession->visit($url);
}
public function login($user, $pass){
$this->minkSession->visit('complete url');
$page = $this->getCurrentPage();
echo $page;
$page->fillField('email', $user); // Enter username.
$page->fillField('password', $pass); // Enter password.
$page->pressButton('Login');
$content = $this->getCurrentPageContent();
$this->assertContains('logout', $content);
}
/**
* #afterClass
*/
public function logout(){
$page = $this->getCurrentPage();
$page->clickLink('logout');
}
}
use PHPUnit\Framework\TestCase;
class MinkPetitionTest extends TestCase
{
use MinkSetup;
public function testSubmitPage(){
$this->login('user', 'pw'); // Login first.
$this->visit('full url');
$page = $this->getCurrentPage(); // Get the page.
echo $page;
$page->fillField('form_ban_id', '1234');
$page->pressButton('form_find_student');
$content = $this->getCurrentPageContent(); // Get page content.
$this->assertContains('<u>No Petitions</u> exist for Some User Student ID: 1234', $content);
}
}
$client = new MinkPetitionTest(); //tried to get something to work
$client->testSubmitPage(); //same here
You need to change your test class like so if you are using the latest phpunit:
...
use PHPUnit\Framework\TestCase;
class MinkPetitionTest extends TestCase
{
...
Can you try that first and see the result?
EDIT #2
Also, your trait file is incorrect. it should be:
trait MinkSetup
{
private $minkBaseUrl;
...
public function visit($url)
{
$this->minkSession->visit($this->minkBaseUrl . $url);
}
...
Try that
I am wondering if someone could help me. I am new to PHP OOP and would like some guidance with using objects.
I am making a login script and the functions I mention below are all from the class file.
Class USER{
public function userLogin($username,$password)
{
$statusY = "Y";
$stmt = $this->connection->prepare("SELECT * FROM tbl_users WHERE user_name=:userName LIMIT 1");
$stmt ->execute(array(":userName"=>$username));
$row = $stmt ->fetch(PDO::FETCH_ASSOC);
if($stmt->rowCount() == 1)
{
$this->_user = $row; // Assign user details
$_SESSION['userSession'] = $row['user_id'];
}
}
public function getUser()
{
return $this->_user;
}
Ok so I have the getUser() function and then assign $this->_user = $row so I can retrieve the user info from the database. Now I want to acheive a couple of things from this but not sure how to go about it.
How would I go about calling $row['user_id'] in another function within the same class?
So basically
public function test()
{
$user_id = $this->_user(user_id);
$username = $this->_user(username);
}
How would I do this correctly?
Also if I want to call the information in a page such as the User Homepage.
$user_home = new USER();
$userID = $user_home->getUser(user_id);
echo $userID;
If anyone could give me some guidance as to how I can move forward with this I would greatly appreciate it. Thanks
Let's start with a basic statement regarding method and class naming: I wouldn't repeat the class' topic over and over again (in the above case "user"), instead just remove it from the method name:
class User
{
private $info= array();
private $authenticated= FALSE;
public function login ($username, $password)
{
// do your stuff
...
// set in case that user name and password have been found
$this->info= $row;
$this->authenticated= TRUE;
}
public function isAuthenticated ()
{
return $this->authenticated;
}
/**
* returns all info from a given user
*/
public function get ()
{
return $this->info;
}
/**
* returns a single field
*/
public function getField ($fieldName) {
if (isset($this->info[$fieldName]) {
return $this->info[$fieldName];
} else {
return FALSE;
}
}
}
Use the getField(FIELD) method to return only a single element of the user's row and get() to return all values.
$user= new User();
$user->login ($username, $password);
if ($user->isAuthenticated()) {
$home= $user->getField('home');
print sprintf('%s\'s home is %s', $username, $home);
}
It's also advisable to create a class for the user database table (i.e. class UserModel) and another one handling user functions (i.e. class UserAuth) which uses the UserModel class. This makes exchanging the underlying authentication source more easy.
Class USER
{
public $_user;
public function userLogin($username,$password)
{
$statusY = "Y";
$stmt = $this->connection->prepare("SELECT * FROM tbl_users WHERE user_name=:userName LIMIT 1");
$stmt ->execute(array(":userName"=>$username));
$row = $stmt ->fetch(PDO::FETCH_ASSOC);
if($stmt->rowCount() == 1)
{
$this->_user = $row; // Assign user details
$_SESSION['userSession'] = $row['user_id'];
}
}
public function getUser()
{
return $this->_user;
}
}
I'm wondering how to receive the results from a function "from the class itself". An example of this is the PDO functions, where I can do the following to get i.e. the last ID:
$db->query($sql);
$id = $db->lastInsertId();
Right now I have to do the following:
$newThread = $forums->newThread('title','category');
$id = $newThread['id'];
Of course this works great, but I have to use the variable $newThread, which I don't want to. How do I save the value in order to call it later?
In case you have problems understanding how the PDO version works, it's roughly like this:
class PDO {
private $lastInsertId;
public function query($sql) {
magic_sql_api_call($sql);
/* here be dragons */
$this->lastInsertId = magic_sql_api_get_last_insert_id();
}
public function lastInsertId() {
return $this->lastInsertId;
}
}
You can create code like this
class Forums {
private $id;
...
function createTread($title, $category) {
$newThread = $forums->newThread($title, $category);
$this->id = $newThread['id'];
}
function lastId() {
return $this->id;
}
}
You can use it
$forums->createTread('title','category');
$id = $forums->lastId();
You probably will need to save $newThread in property too.
We are trying to understand the best way to use mysqli/other classes in multiple custom classes so that we don't instantiate a new object every time.
Is the code below the best/correct way of doing this?
The functions are only examples.
Thank you :)
<?php
class Base {
public function __get($name) {
if($name == 'db'){
$db = new mysqli('**', '*s', '*', '*');
$this->db = $db;
return $db;
}
if($name == 'blowfish'){
$blowfish = new PasswordHash(8, true);
$this->blowfish = $blowfish;
return $blowfish;
}
}
}
class A extends Base {
public function validate($username, $password) {
$query = $this->db->query("SELECT * FROM users");
return $query->num_rows;
}
public function password($password)
{
return $this->blowfish->HashPassword($password);
}
}
class PasswordHash {
public function __construct($iteration_count_log2, $portable_hashes) { }
public function HashPassword($password) {
return $password;
}
}
$a = new A;
echo $a->validate('test','test'); // returns number rows count as expected
echo $a->password('password123'); // returns password123 as expected
?>
You are/should probably be more interested in Dependency Injection instead of creating a tight coupling of Base|A and the MySQL database.