i have private class with array :
class Whois{
private $whoisServers = array(
"ac"=> "whois.nic.ac",
"ae" => "whois.nic.ae",
"tech" => "whois.nic.tech",
"yu" => "whois.ripe.net");
}
now, possible i get array() for private $whoisServers from database?
Now make an object of a class and access to public function.
<?php
class Whois{
private $whoisServers = array(
"ac"=> "whois.nic.ac",
"ae" => "whois.nic.ae",
"tech" => "whois.nic.tech",
"yu" => "whois.ripe.net");
/*
!----------------------------------------------
! Getting Private Server List Using Public Function
! #getter
!----------------------------------------------
*/
public function getWhichServers()
{
return $this->whoisServers;
}
/*
https://github.com/arif98741
*/
}
$object = new Whois();
$serverlist = $object->getWhichServers();
Related
i was playing around with spatie dto library and i found myself with a problem.
how do i cast an array to a subobject?
use Spatie\DataTransferObject\DataTransferObject;
class OtherDTOCollection extends DataTransferObject {
public OtherDto $collection;
}
class OtherDTO extends DataTransferObject {
public int $id;
public string $test;
}
class MyDTO extends DataTransferObject {
public OtherDTO $collection;
}
class MyDTO2 extends DataTransferObject {
public OtherDTOCollection $collection;
}
// WORKS
$MyDTO = new MyDTO(
collection: [
[
'id' => 1,
'test' => 'test'
],
[
'id' => 1,
'test' => 'test'
]
]
);
// DOESN'T WORK
$MyDTO2 = new MyDTO2(
collection: [
[
'id' => 1,
'test' => 'test'
],
[
'id' => 1,
'test' => 'test'
]
]
);
here's the relevant code, how can i make it work so that i have an array of objects?
thanks
You need to use the CastWith class form Spatie Attributes. .
use Spatie\DataTransferObject\Casters\ArrayCaster;
use Spatie\DataTransferObject\Attributes\CastWith;
This example will give you array of dto objects. /** #var \DTO\PrefixListItem[] */ comment has key role, type here full namespace, not on the top with use
namespace \DTO;
use Spatie\DataTransferObject\DataTransferObject;
class PrefixListResult extends DataTransferObject
{
/** #var \DTO\PrefixListItem[] */
public ?array $list = [];
public ?string $server_time = null;
public ?int $code = null;
public ?string $message = null;
public ?array $details = [];
}
namespace \DTO;
use Spatie\DataTransferObject\DataTransferObject;
class PrefixListItem extends DataTransferObject
{
public string $imsi_prefix;
public string $operator;
public int $min_sim_active_days;
public int $max_sim_active_days;
public bool $call_forwarding;
}
I need to serialize an object as its own property (it's type is array), I mean that the object has an array property books, and after transforming it I want to skip the books key, so the structure will be more flat [book1, book2] (not [books => [book1, book2]]. I have the following classes:
<?php
class Store
{
private ?BooksCollection $booksCollection = null;
public function __construct(?BooksCollection $booksCollection = null)
{
$this->booksCollection = $booksCollection;
}
public function getBooksCollection(): ?BooksCollection
{
return $this->booksCollection;
}
}
class BooksCollection
{
/** #var Book[] */
private array $books;
public function __construct(Book ...$books)
{
$this->books = $books;
}
public function getBooks(): array
{
return $this->books;
}
}
class Book
{
private string $title;
public function __construct(string $title)
{
$this->title = $title;
}
public function getTitle(): string
{
return $this->title;
}
}
and serialization config:
Store:
exclusion_policy: ALL
properties:
booksCollection:
type: BooksCollection
BooksCollection:
exclusion_policy: ALL
properties:
books:
type: array<int, Book>
Book:
exclusion_policy: ALL
properties:
title:
type: string
The test I want to pass:
<?php
use JMS\Serializer\ArrayTransformerInterface;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
class StoreSerializeTest extends KernelTestCase
{
/** #var ArrayTransformerInterface */
private $serializer;
protected function setUp(): void
{
self::bootKernel();
$this->serializer = self::$kernel->getContainer()->get('jms_serializer');
}
public function testSerialization(): void
{
$store = new Store(new BooksCollection(new Book('Birdy'), new Book('Lotr')));
$serializedStore = $this->serializer->toArray($store);
$storeUnserialized = $this->serializer->fromArray($serializedStore, Store::class);
self::assertSame(
[
'books_collection' => [
['title' => 'Birdy'],
['title' => 'Lotr']
]
],
$serializedStore
);
self::assertEquals($store, $storeUnserialized);
}
}
As you can see below the test is failing. How can I get rid of one nesting 'books'?
The main idea I had, was to use EventSubscriberInterface and onPreSerialize event, but I really can't figure out how can I replace an object BooksCollection with an array made of its own property books. Is there anyone who already know how to do it?
Finally, I figured it out. I implemented SubscribingHandlerInterface
<?php
use JMS\Serializer\Context;
use JMS\Serializer\GraphNavigatorInterface;
use JMS\Serializer\Handler\SubscribingHandlerInterface;
use JMS\Serializer\JsonDeserializationVisitor;
use JMS\Serializer\JsonSerializationVisitor;
use Book;
use BooksCollection;
class BooksCollectionHandler implements SubscribingHandlerInterface
{
public static function getSubscribingMethods(): array
{
return [
[
'type' => BooksCollection::class,
'format' => 'json',
'method' => 'serialize',
'direction' => GraphNavigatorInterface::DIRECTION_SERIALIZATION,
],
[
'type' => BooksCollection::class,
'format' => 'json',
'method' => 'deserialize',
'direction' => GraphNavigatorInterface::DIRECTION_DESERIALIZATION,
]
];
}
public function serialize(
JsonSerializationVisitor $visitor,
BooksCollection $booksCollection,
array $type,
Context $context
) {
return $visitor->visitArray($booksCollection->getBooks(), ['name' => 'array'], $context);
}
public function deserialize(
JsonDeserializationVisitor $visitor,
array $data,
array $type,
Context $context
): BooksCollection {
$collection = [];
foreach ($data as $book) {
$collection[] =
$visitor->getNavigator()->accept($book, ['name' => Book::class], $context);
}
return new BooksCollection(...$collection);
}
}
service config:
books_handler:
class: BooksCollectionHandler
tags:
- { name: jms_serializer.subscribing_handler }
I am trying to access this data from outside of a class. The code works when it is not class based, but once I convert it to classes it stops. I want to be able to access the data as array single indexes. The code is below:
//Database connection that is working
class Database {
private $_connection;
private static $_instance; //The single instance
private $_host = "localhost";
private $_username = "root";
private $_password = "testuser";
private $_database = "testpassword";
/*
Get an instance of the Database
#return Instance
*/
public static function getInstance() {
if(!self::$_instance) { // If no instance then make one
self::$_instance = new self();
}
return self::$_instance;
}
// Constructor
private function __construct() {
$this->_connection = new mysqli($this->_host, $this->_username,
$this->_password, $this->_database);
// Error handling
if(mysqli_connect_error()) {
trigger_error("Failed to conencto to MySQL: " . mysqli_connect_error(),
E_USER_ERROR);
}
}
public function result()
{
echo $this->query;
}
// Magic method clone is empty to prevent duplication of connection
private function __clone() { }
// Get mysqli connection
public function getConnection() {
return $this->_connection;
}
}
//select statement that is not working as a class
class getText
{
private static $_instance;
private $field;
private $result;
public static function getInstance() {
if(!self::$_instance) {
self::$_instance = new self();
}
return self::$_instance;
}
public function __construct()
{
$db = Database::getInstance();
$mysqli = $db->getConnection();
$sql = "SELECT * FROM template_text_boxes WHERE idtemplate_text_boxes='61'";
$this->result = mysqli_query($mysqli, $sql);
if ($this>result) {
while ($row = mysqli_fetch_assoc($this->result)) {
$this->field[] = array('text1' => $row['text1'], 'text2' => $row['text2'], 'text3' => $row['text3'], 'text4' => $row['text4'], 'text5' => $row['text5'], 'text6' => $row['text6'], 'text7' => $row['text7'], 'text8' => $row['text8'], 'text9' => $row['text9'], 'text10' => $row['text10'], 'text11' => $row['text11'], 'text12' => $row['text12'], 'text13' => $row['text13'], 'text14' => $row['text14'], 'text15' => $row['text15'], 'text16' => $row['text16'], 'text17' => $row['text17'], 'text18' => $row['text18'], 'text19' => $row['text19'], 'text20' => $row['text20'], 'text21' => $row['text21'], 'text22' => $row['text22'], 'text23' => $row['text23'], 'text24' => $row['text24'], 'text25' => $row['text25'], 'text26' => $row['text26'], 'text27' => $row['text27'], 'text28' => $row['text28'], 'text29' => $row['text29'], 'text30' => $row['text30'], 'text31' => $row['text31'], 'text32' => $row['text32'], 'text33' => $row['text33'], 'text34' => $row['text34'], 'text35' => $row['text35'], 'text36' => $row['text36'], 'text37' => $row['text37'], 'text38' => $row['text38'], 'text39' => $row['text39'], 'text40' => $row['text40'], 'text41' => $row['text41'], 'text42' => $row['text42'], 'text43' => $row['text43'], 'text44' => $row['text44'], 'text45' => $row['text45'], 'text46' => $row['text46'], 'text47' => $row['text47'], 'text48' => $row['text48'], 'text49' => $row['text49'], 'text50' => $row['text50'], 'text57' => $row['text57'], 'text58' => $row['text58']);
}
}
}
public static function get_text($this->field, $x)
{
echo ->field[0][$x];
}
public static function text($field, $x)
{
return -> field[0][$x];
}
}
//how I want to access each database column
$getText ->text($field,'text49');
$getText = new getText();
//
class Settings {
public $constants = [
'database' => [
'APP_DB_HOST' => 'localhost'
],
];
}
class Constants extends Settings {
public $database = [
'APP_DB_HOST' => $settings->constants['database']['APP_DB_HOST'], // not working
];
}
I need to access parent class array values in child class. but this $settings->constants['database']['APP_DB_HOST'] is not working for some reason.
Here is the working solution
<?php
class Settings {
public $constants = [
'database' => [
'APP_DB_HOST' => 'localhost'
],
];
}
class Constants extends Settings {
public $database;
public function __construct(){
$database = [
'APP_DB_HOST' => $this->constants['database']['APP_DB_HOST'], // working
];
}
}
print_r(new Constants());
outputs:
Constants Object
(
[database] =>
[constants] => Array
(
[database] => Array
(
[APP_DB_HOST] => localhost
)
)
)
as per your comment,
if you want to do it in other class function, you can do that as well.
class Constants extends Settings {
public $database;
public function useParentHost(){
$this->database = [
'APP_DB_HOST' => $this->constants['database']['APP_DB_HOST'], // working
];
return $this->database;
}
}
and then
$test = new Constants();
print_r($test->useParentHost());
you have to declare some function to use $this, without/outside the function this will cause an error.
The variable $settings does not exist, perhaps you mean $this?
$this->constants['database']['APP_DB_HOST'];
Enjoy.
I've got a ResponseGrid object and I want to encode it in Json. This object has got a $row variable inside, which will contain an array of Document objects.
I implemented JsonSerializable interface and jsonSerialize() method in both ResponseGrid and Document.
What I've got is this:
ResponseGrid.php:
require_once ROOT_DIR . "/business/models/Document.php";
class ResponseGrid implements JsonSerializable {
private $sEcho;
private $iTotalRecords;
private $iTotalDisplayRecords;
private $rows; // This will contain an Array of Documents
public function jsonSerialize() {
return [
'sEcho' => $this->sEcho,
'iTotalRecords' => $this->iTotalRecords,
'iTotalDisplayRecords' => $this->iTotalDisplayRecords,
'rows' => json_encode($this->rows), //This will cause troubles
];
}
}
Document.php:
class Document implements JsonSerializable {
private $id;
private $name;
private $description;
private $contentId;
public function jsonSerialize() {
return [
'id' => $this->id,
'name' => $this->name,
'description' => $this->description,
'contentId' => $this->contentId,
];
}
}
If I do an echo of a ResponseGrid object filled with two Documents in the $row array, I get this
echo json_encode($responseGrid);
{"sEcho":1,"iTotalRecords":27,"iTotalDisplayRecords":4,"rows":"{\"1\":{\"id\":1,\"name\":\"Greece\",\"description\":\"descGreece\",\"contentId\":2},\"2\":{\"id\":2,\"name\":\"Rome\",\"description\":\"descRome\",\"contentId\":3}}"}
Why is that? Am I doing it wrong? What are all those backslashes?