0
I’m facing a problem to handle my classes with the composer autoload
.
All calls are made through Jquery, then it calls a PHP document that should assemble the class page and call the function I need.
Example:
I have a login page, when I fill in all fields it will make the call through the file that is in JS.
Example of button
:
<button type="button" class="btn btn-primary" name="btn-login" id="btn-login" onclick="JavaScript:getClasseLogin().fazerLogin()">
Entrar
</button>
When he makes the call from getClasseLogin().fazerLogin()
, everything is working perfectly, it can call the URL normally, follows code:
fazerLogin: function () {
$("#btn-login").click(function () {
var data = $("#login-form").serialize();
$.ajax({
type : 'POST',
url : 'classes/retorna_metodo_ajax.php?classe=Cliente&metodo=validaUsuario',
data : data,
dataType: 'json',
beforeSend: function()
{
$("#btn-login").html('Validando ...');
},
success : function(response){
if(response.codigo == "1"){
console.log("entra no if");
$("#btn-login").html('Entrar');
$("#login-alert").css('display', 'none')
window.location.href = "home.php";
}
else{
console.log("entra no else");
$("#btn-login").html('Entrar');
$("#login-alert").css('display', 'block')
$("#mensagem").html('<strong>Erro! </strong>' + response.mensagem);
}
}
});
})
}
The whole problem starts now...
The URL he is sending is as follows:
https://jkads.com.br/bootstrap/classes/retorna_metodo_ajax.php?classe=Clientes&metodo=validaUsuario
In there he passes to the document retornar_metodo_ajax.php
, that is this way:
<?php
require_once "../vendor/autoload.php";
ob_start();
//$params = $_GET['params'];
$classe = $_GET['classe'];
$metodo = $_GET['metodo'];
var_dump($classe);
var_dump($metodo);
if($classe == null || $metodo == null) {
die("Não possui classe ou método");
} else {
$_nome = htmlentities(strip_tags($_GET["classe"]), ENT_COMPAT, "UTF-8");
if (!file_exists($classe . ".php")) {
die("Classe não encontrada.");
}
$_class = new $classe();
echo $_class->$metodo();
}
It enters the document, can do the proper checks, but when it tries to insert the class it returns the error:
Fatal error: Class 'Customers' not found in /home/jkadsco1/Domains/jkads.com.br/public_html/bootstrap/classes/retorna_metodo_ajax.php on line 18
The document Clientes.php
is this:
<?php
namespace Clientes;
class Clientes {
function __construct()
{
return '';
}
public function validaUsuario($params)
{
echo "<script>alert('Chegou aqui também')</script>";
$parametros = explode(",", json_decode($params));
echo "<script>alert(".$parametros.")</script>";
return 1;
}
}
He can not call the class, because unfortunately, every time I will make use of a class in a document, I need to use as below:
$cliente = new \Clientes\Clientes();
$cliente->validaUsuario();
When the document retorna_metodo_ajax.php
tries to do the new()
he is not succeeding as he cannot find without specifying how new \Namespace\Classe()
.
Is there any way to make every time I call the new Class()
it just calls for the specified class instead of new \Namespace\Class()
?
I’ve tried to give a include()
with the class document, but it does not work. Try to concatenate as $_class = new "\\".$classe."\\".$classe()
didn’t work either.
Can someone shed some light on that?
Folder structure:
.
├── classes
│ ├── BaseBD.php
│ ├── BdMySql.php
│ ├── Cadastro.php
│ ├── classNoticias.php
│ ├── Clientes.php
│ ├── conec.php
│ ├── ConecxaoBd.php
│ ├── conexao.php
│ ├── Datas.php
│ ├── funcoesGerais.php
│ ├── Globals.php
│ ├── GravarLogs.php
│ ├── Menus.php
│ ├── News.php
│ ├── Noticias.php
│ └── retorna_metodo_ajax.php
│
├── composer.json
├── composer.lock
├── index.php
└── vendor
└── autoload.php
Composer.json
{
"autoload": {
"classmap": [
"classes"
]
}
}
About
new Class()
instead ofnew \Namespace\Class()
, if you don’t want namespaces then don’t write with namespaces on anything, it already does, but if you want to use namespaces with "nicknames" then read: https://answall.com/a/151492/3635– Guilherme Nascimento
Now I have a doubt, so that both OOP in something simple, in something that actually could be done in a simple, understandable and organized way that does not need OOP. The OOP without real need is just a waste, most use, but not by necessity, was someone told them a FAKENEWS, "OOP is better". "Better" depends on context and for your case does not improve at all, on the contrary, complicates, is unnecessary and nor aims to understand or function as OO. Many also use OO without need to make something look more elegant, which turns out to be a trap.
– Guilherme Nascimento
It’s a college project, I need to make an entire system using OO, otherwise it won’t be accepted. As it has been specified that everything must go through "global" JS and be sent to the same document, treated and sent to the class, I need to follow this specification :/
– user171156
The colleges then are not good teachers, teaching OOP not OO, I mean writing in OO is not necessarily a "object orientation", in practice it is to work, in reality you are not doing anything that is really for the purpose of the existence of OO, after all when OO was created it had a reason to exist, and in your case it is not even following this. But the criticism about this is the part, about your problem I left in the first comment.
– Guilherme Nascimento
unfortunately I have to agree... My teacher is like "I have my favorites, the rest turns"... His content is weak, but unfortunately a quality college is much more expensive... Regarding doubt, I read your post there, I’m trying to make it work here, but still says that does not find the class... I ran the test calling a function by
new Class()
and it’s working, I removed theuse()
and thenamespace()
documents and is now working to make the call, however, byretorna_metodo_ajax.php
he’s still not getting the function call– user171156
In autoload find wrong and unnecessary use
if (!file_exists($classe . ".php")) {
 die("Classe não encontrada.");
 }
, when a class is inaccessible the only error should be the one that is already occurring, this double check that you did only takes more time from the script and really doesn’t even have to exist. For the record, if you’re wearingvendor/autoload.php
means you are using Poser, am I correct? There is acomposer.json
in your briefcase?– Guilherme Nascimento
Yes, there is, when I asked in class about this, practically what you said, he only replied that he knew what he was doing, that 15 years of experience spoke for itself... But anyway... Yes, there is
composer.json
– user171156
So the problem is in the configuration of Composer.json, if you do not configure your custom classes correctly in it, they will not be found... The person may have 20 years of experience and still have learned everything wrong, but really the experience makes a difference yes, of course if you are humble and accept that a previous way of doing things was wrong and want to change, maintain a certain level of skepticism when someone comes up with a magic solution trying to convince you to use it and without any technical argument. Evolution starts with each one, but I like to help others to tread better.
– Guilherme Nascimento
Man... I’d like my teacher to talk to you kkkk, he really has a lot of experience, but the way I see it, if he keeps it up, he’ll soon lose his job, Because 80% of the class is pissed that they have a middle/advanced knowledge and are only there on account of the certificate and have to listen to these things of his... I’m gonna go check the setting it right so I can finish this soon hahaha
– user171156
Put the folder structure you use similar to this https://cmatskas.com/generate-ascii-folder-structures-for-windows-with-tree/ in the question, but with its folders of course, you do not need to use the specified program to generate, just copy and paste and adjust your folders and copy the content of Composer.json and put it in the question too, I’m sure I can help you with that.
– Guilherme Nascimento
I added the folder structure, by Ubuntu it is simpler, just use the
tree
inside the briefcase :)– user171156
Let’s go continue this discussion in chat.
– Guilherme Nascimento
@Guilhermenascimento, I answered the chat for you
– user171156