Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 months ago.
Improve this question
I really searched too much but i couldn't find anything. I'm newbie to classes that's why I'm getting trouble :)
My class is like below:
class Instagram
{
public array $account = [];
public function get_instagram_business_accounts(): array
{
return db()->query("SELECT followers_count FROM instagram_business_accounts ORDER BY username")->fetchAll();
}
public function get_followers_count()
{
return Miscellaneous::number_format($this->account["followers_count"]);
}
}
I'm using the above class like this:
$accounts = new Instagram();
foreach($accounts->get_instagram_business_accounts() AS $account){
$accounts->account = $account;
echo $accounts->get_followers_count();
}
But I want to use like this:
$accounts = new Instagram();
foreach($accounts->get_instagram_business_accounts() AS $account){
echo $account->get_followers_count();
}
I want to use $account as an object. How can I do this?
Best Regards,
=======
EDIT
I updated my main class like below:
class Instagram
{
public function get_instagram_business_accounts(): array
{
$accounts = db()->query("SELECT followers_count FROM instagram_business_accounts ORDER BY username")->fetchAll();
$return = [];
foreach($accounts AS $account){
$return[] = new InstagramAccount($account);
}
return $return;
}
}
And my InstagramAccount class is below:
class InstagramAccount
{
private int $followers_count;
public function __construct(array $Instagram)
{
foreach($Instagram AS $key=>$value){
$this->{$key} = $value;
}
}
public function get_followers_count(): string
{
return Miscellaneous::number_format($this->followers_count);
}
}
Now I do what i want, right?
get_followers_count() is a method of class Instagram. In your second code you try to call this method from $account which is an array. That doesn't work
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
What would be the correct way to handle the types of state that an object can have in an application?
For example, if i have an AcceptanceCriteria class, i need to verify if it is accepted, rejected or pending.
I usually do it by returning numbers that represent the state, but it does not seem like a good form, it can be confusing.
for example:
class AcceptanceCriteria
{
const PENDING = 0;
const ACCEPTED = 1;
const REJECTED = 2;
protected $state = self::PENDING;
public function accept():void
{
$this->state = self::ACCEPTED;
}
public function reject():void
{
$this->state = self::REJECTED;
}
public function state():int
{
return $this->state;
}
}
I need to check the state frequently and also show it in the front, what is a better way to do it? I dont want to check in the front if and acceptance criteria state is 0, 1 or 2 for do something.
How about some accessors that return booleans rather than ints so your algorithm is completely encapsulated?
class AcceptanceCriteria
{
const PENDING = 0;
const ACCEPTED = 1;
const REJECTED = 2;
protected $state = self::PENDING;
public function accept():void
{
$this->state = self::ACCEPTED;
}
public function reject():void
{
$this->state = self::REJECTED;
}
// Accessors
public function is_rejected():bool
{
return self::PENDING == $this->state;
}
public function is_accepted():bool
{
return self::ACCEPTED == $this->state;
}
public function is_rejected():bool
{
return self::REJECTED == $this->state;
}
}
Its good way to use strongly typed enums. You can use splEnum or smart implementation from My C-Labs.
First move your states to separated enum class
<?php
use MyCLabs\Enum\Enum;
class AcceptanceCriteriaStateEnum extends Enum
{
private const PENDING = 0;
private const ACCEPTED = 1;
private const REJECTED = 2;
}
then you can modify your class like bellow
class AcceptanceCriteria
{
protected $state = AcceptanceCriteriaStateEnum::PENDING;
public function setState(AcceptanceCriteriaStateEnum $state):void
{
$this->state = $state;
}
public function getState():int
{
return $this->state;
}
public function isInState(AcceptanceCriteriaStateEnum $checkState):bool
{
return $this->state == $checkState;
}
}
for checking state you can use method isInState which return boolean
$obj = new AcceptanceCriteria();
$obj->setState(AcceptanceCriteriaStateEnum::ACCEPTED);
// check status
echo $obj->isInState(AcceptanceCriteriaStateEnum::ACCEPTED);
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I had one lesson in OOP which included messaging between classes. On the tutorial, the guy just showed var_dump output version of that. I wanted to play with the code and change from var_dump to echo output, because it would me more useful in future. I just couldn't find any solution so you guys are my only option. Here's the code.
<?php
class Person {
protected $name;
public function __construct($name)
{
$this->name = $name;
}
public function getName()
{
return $this->name;
}
}
class Business {
// adding Staff class to Business
public function __construct(Staff $staff)
{
$this->staff = $staff;
}
// manual hire(adding Person to Staff)
public function hire(Person $person)
{
// add to staff
$this->staff->add($person);
}
// fetch members
public function getStaffMembers()
{
return $this->staff->members();
}
}
class Staff {
// adding people from Person class to "member" variable
protected $members = [];
public function __construct($members = [])
{
$this->members = $members;
}
// adding person to members
public function add(Person $person)
{
$this->members[] = $person;
}
public function members()
{
return $this->members;
}
}
// you can also create an array with this method
$bros = [
'Bro',
'Zdenko',
'Miljan',
'Kesten'
];
// pretty simple to understand this part
$employees = new Person([$bros]);
$staff = new Staff([$employees]);
$business = new Business($staff);
var_dump($business->getStaffMembers());
// or the print_r, it doesn't matter
print_r($business->getStaffMembers());
?>
Try to loop through the array and echo out every single value.
$array = $something //your assignment here
foreach($array as $key => $value ){
echo "$key => $value\n";
}
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
I would like to improve my php web development, so, i would like to know what is your best pratice when you make a new object class ?
I have a sample of a class object. I would like to know how do you do this. If it's good or bad.
Class Contact extends Object {
public $id;
public $firstname = 'john';
public $lastname = 'doe';
public function __construct($id_contact = NULL) {
parent::__construct($id_contact);
if ($this->id) {
$this->fullname = $this->firstname . ' '.$this->lastname
}
}
public static function getFullName($id_contact){
$cnt = new Contact($id_contact);
return $cnt->fullname;
}
}
And use the method like this in different controller :
$cnt_fullname = Contact::getFullName($id);
Or it's better to load new object in the controller
$cnt = new Contact($id);
$cnt_fullname = $cnt->fullname;
Thanks you for your reply.
The way I make good classes:
class Good
{
}
So, for example best way
class Getter {
private static $contact = null
public static function getContactObj($id) {
if(!is_null(self::$contact)) {
return self::$contact;
}
self::$contact = new Contact($id);
return self::$contact;
}
}
and your class contact
Class Contact extends Object {
public $id;
public $firstname = 'john';
public $lastname = 'doe';
public function setId($id) {
$this->id = $id;
return $this;
}
public function getFullName()
$this->fullname = $this->firstname . ' '.$this->lastname
return $this->fullname;
}
}
And you can use this construction in over controllers:
Getter::getContactObj()
->setId(1)
->getFullName();
Getter::getContactObj()
->setId(2)
->getFullName();
Getter::getContactObj()
->setId(3)
->getFullName();
and etc.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
it's probably quite a noob question, but I'm not an expert PHP developer and I was wondering what is the best (efficient, logical) way to write the following code:
function validate_1 ( $input ) {
if ( mycondition ) {
return $input;
}
}
function validate_2 ( $input ) {
if ( myOtherCondition ) {
return $input;
}
}
function validate ( $input ) {
if ( validate_1( $input ) ) {
return validate_1( $input );
} else if ( validate_2( $input ) ) {
return validate_2( $input );
} else {
return validate_last( $input );
}
}
validate( 'a value' );
in this way I'm always executing the functions twice. Is that fine or is there a better way (php >= 5.2)?
You can try this:
http://dsheiko.com/subpage/chain-of-responsibility-pattern
or do it like this with classes:
abstract class Validator {
public function validate($args);
}
class Vali1 extends Validator {
public function validate($args){
#validate
return $bool;#true or false
}
}
class Vali2 extends Validator {
public function validate($args){
#validate
return $bool;#true or false
}
}
$validators = array(new Vali1,new Vali2);
$validated=null;
foreach($validators as $validator){
$validated = $validator->validate($args);
}
or with functions :
$validators = array(
function($args) { retrun $bool;},
function($args) { retrun $bool;},
function($args) { retrun $bool;}
);
$validated=null;
foreach($validators as $validator){
$validated = $validator($args);
}
But that is just the basics. And there are more ways to rome.
update:
$count = count($validators);
$current = 0;
do{
$result = $validators[$current++]($args);
}while(!$result && $current < = $count);
and then return $input in the function or NULL on not valid
Before you write such unreadable code, use some validation strategies like the Symfony validation component or just keep it simple and try to encapsulate your code in a class (e.g. OrderValidator) with one public function validate($data) and keep this method clean by writing small readable private functions you use in that public function.
Think of someone trying to understand the code. He is going to have a look at the validate method and if it's like this ...
public function validate($data) {
return
$this->isEachOrderClosed($data)
&& $this->hasAtLeastOneCustomer($data)
&& $this->isNotSent($data)
;
}
... he maybe needn't read the private methods and everything is clear.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I ask your advise.
In my php file there are some classes.
class Template {
public $id;
public $title;
public $text;
public $description;
public $data = array();
public $content_html;
public $width_content = 500;
public $type;
public $time;
public $user;
public $category;
protected $CI;
// The next code works for a one element of array $data
function __construct($data = array()){
$this->title = $data['title'];
$this->text = $data['text'];
$this->category = $data['category'];
$this->type = $data['type'];
$this->time = $data['time'];
$this->CI =& get_instance();
$this->user = new InformationUser($data);
}
class Articles extends Template {
}
class News extends Template {
}
class Init {
public $posts = array('type' => 2);
}
The start point of my classes is a class Init.
Inside this class there is array of users posts.
In each element array there is a type value, which define what object class I must create.
For example:
class Init {
function define(){
foreach($this->posts as $val){
if($val['type'] == 2){
$article = new Articles($val);
//TODO $articles
} else if($val['type'] == 3){
$news = new News($val);
//TODO $news
}
}
}
}
I know that is variant is wrong, better to put all array posts() to class. But I can not do this.
I need, that for different type of element of array - to work separate class (for news - News class, article - class Article etc.)
What do you advise me?
From the minimal info provided.. I assume you are looking for something like this:
<?php
class Init {
public static function define($type, $text)
{
switch($type) {
case 1:
return new Articles($text);
break;
case 2:
return new News($text);
break;
default:
throw new Exception('Undefined type');
}
}
}
// $template = Init::define(1, 'article text');
// $template = Init::define(2, 'news text');