I'm doing my first project trying to learn Laravel and I've come to the point where I want to create an object.
I've created it and tried it out and it works as I want it to, but where do I put it? As of now it lies directly in my controller, but it doesn't feel right and besides that I think it messes up the code. Where are you actually supposed to put it? Is there such a place?
This is how my code looks and as you can see it is called "Hosts" and it's placed at the top of the page:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class Host {
public $ipv4, $mac;
public function __construct($ipv4, $mac){
$this->ipv4 = $ipv4;
$this->mac = $mac;
}
}
class PagesController extends Controller
{
public function index(){
libxml_use_internal_errors(true); //ignore invalid HTML tag warnings
$dom = new \DOMDocument();
// Check that there's actually a file to load
if(!$dom->loadHTMLFile('\\\192.168.1.201\root\test.xml')){
die('error loading xml');
}
// Loop through all <host> tags
foreach ($dom->getElementsByTagName('host') as $hostKey => $host) {
$hostAttributes = array();
// Check for <address> tags and loop through them as well
foreach ($host->getElementsByTagName('address') as $addressKey => $addressValue) {
// Check that there is an <addrtype> and <addr> tag
if($addressValue->getAttribute('addrtype') && $addressValue->getAttribute('addr')){
// Put that into the array $hostAttributes
$hostAttributes[$addressValue->getAttribute('addrtype')] = $addressValue->getAttribute('addr');
}
}
// Check for the keys 'ipv4' and 'mac' in $hostAttributes
if(array_key_exists('ipv4', $hostAttributes) && array_key_exists('mac', $hostAttributes)) {
$hosts[$hostKey] = new Host($hostAttributes['ipv4'], $hostAttributes['mac']);
}
}
// set data
$data = [
'hosts' => $hosts
];
// return view
return view('pages.index')->with('data', $data);
}
}
The file is located in "/app/Http/Controllers/PagesController.php" and I'm running Laravel 5.7.21