I'm very very new in Zend Framework.
I wanted delete a row in db via $.post in jQuery that was not done.
I also did a lot of research on Google and Youtube, but I did not get result, Unfortunately.
Please help me.
ZF version: 1.11.2
application/Bootstrap.php:
protected function _initDb(){
$con=array('host'=>'127.0.0.1','username'=>'root','password'=>'','dbname'=>'sample_db');
$db=Zend_Db::factory('Pdo_Mysql',$con);$db->query("SET NAMES 'utf8'");
Zend_Registry::set('db',$db);
}
application/controllers/DashboardController.php:
public function indexAction(){
$this->_helper->layout->setLayout('a');
}
application/views/scripts/dashboard/index.phtml:
DELETE
public/js/0.js:
function deleteTest(id){
if(confirm('Are you sure?'))
$.post('http://127.0.0.1/Sample4/application/models/Guestdb.php',{funcName:'Delete_Test',id:id},function(r){alert(r)})
}
application/models/Guestdb.php:
class Model_Guestdb{
public function Delete_Test(){
$db=Zend_Registry::get('db');
$r=$db->query("DELETE FROM `prac` WHERE `id`='".trim((new Zend_Filter_Decrypt(array('adapter'=>'mcrypt','key'=>'thisisakeytolock','vector'=>'myvector')))->filter(hex2bin($this->getRequest()->getPost()['id'])))."'");
echo$r?'t':'f';
}
}
$a=new Model_Guestdb();
if(isset($_POST['funcName']))call_user_func(array($a,$_POST['funcName']));
elseif(isset($_GET['funcName']))call_user_func(array($a,$_GET['funcName']));
Output:
Fatal error: Uncaught Error: Class 'Zend_Registry' not found in C:\xampp\htdocs\Sample4\application\models\Guestdb.php:6 Stack trace: #0 C:\xampp\htdocs\Sample4\application\models\Guestdb.php(35): Model_Guestdb->Delete_Test() #1 {main} thrown in C:\xampp\htdocs\Sample4\application\models\Guestdb.php on line 6
Sorry for my english
Please help me
Thanks in advance
I solved this problem as follows:
application/views/scripts/dashboard/index.phtml:
DELETE
public/js/0.js:
function del(id){
if(confirm('Are you sure?'))
$.post('ajax',{func:'del',table:'prac',id:id},
function(r){r=='t'?location.reload():alert('Error!')})
}
application/controllers/DashboardController.php:
<?php
class DashboardController extends Zend_Controller_Action{
public function ajaxAction(){
$this->_helper->layout->disableLayout();
$ajax=$this->getRequest()->getPost();$func=$ajax['func'];
(new Model_Guestdb)->$func($ajax['table'],$ajax['id']);
}
}
application/models/Guestdb.php:
class Model_Guestdb{
public function del($table,$id){
echo Zend_Registry::get('db')->query
("DELETE FROM `$table` WHERE `id`='$id'")?'t':'f';
}
}
Thanks for friends comments.
Related
Trying to get to grips with Mocking and test cases, I want to test that a Mailable TestMail is sent from company#company.com, the documentation provides hasTo, hasCc, and hasBcc but doesn't look like it uses something like hasFrom. Is there any solutions to this?
https://laravel.com/docs/9.x/mocking#mail-fake
public function testEmailAlwaysFrom()
{
Mail::fake();
Mail::to('foo#bar.com')->send(new TestMail);
Mail::assertSent(TestMail::class, function ($mail) {
return assertEquals('company#company.com', $mail->getFrom());
// return $mail->hasTo($user->email) &&
// $mail->hasCc('...') &&
// $mail->hasBcc('...');
});
}
MailFake doesn't provide hasFrom method in the class and therefore will return false.
The workaround below however doesn't work when using the environmental variable MAIL_FROM_ADDRESS, ->from() has to be called within build().
A couple of GitHub issues have been reported suggesting a workaround below:
https://github.com/laravel/framework/issues/20056
https://github.com/laravel/framework/issues/20059
public function testEmailAlwaysFrom()
{
Mail::fake();
Mail::to('foo#bar.com')
->send(new TestMail);
Mail::assertSent(TestMail::class, function ($mail) {
$mail->build(); // <-- workaround
return $mail->hasTo('foo#bar.com') and
$mail->hasFrom('company#company.com');
});
}
I am testing my laravel project with dusk.
I am trying to inject a dependency in a test like that :
....
class PasswordLostTest extends DuskTestCase
{
private $passwordResetRepository;
public function __construct(PasswordResetRepository $passwordResetRepository)
{
$this->passwordResetRepository = $passwordResetRepository;
}
.....
When I run the test with php artisan dusk .\tests\Browser\PasswordLostTest.php, I have this error :
Fatal error: Uncaught ArgumentCountError: Too few arguments to function Tests\Browser\PasswordLostTest::__construct(), 0 passed in D:\Workspace\classified-ads-mpa\vendor\phpunit\phpunit\src\Framework\TestBuilder.php on line 138 and exactly 1 expected in D:\Workspace\classified-ads-mpa\tests\Browser\PasswordLostTest.php:20
What is the problem ? Is it because I am in a test script ?
TestCases are not instantiated by the container. Secondly your app is not bootstrapped before setup has been called, the constructor is called first. Making your example technically impossible. Instead use resolve() or app()->make(), in the setup method to do what you want.
Your app is bootstrapped to the parent test cases setup, so calling parent::setUp(); is essential.
public function setUp()
{
parent::setUp();
$this->passwordResetRepository = resolve(PasswordResetRepository::class);
}
Here is the solution :
public function setUp(): void
{
parent::setUp();
$this->passwordResetRepository = resolve(PasswordResetRepository::class);
}
WARNING : the void is mandatory. That's why it did not work !
Many thanks to mrhn who guided me for this problem !
I am a bit confused about my folder structure for the scraping code. Using console/commands, not the controller. So, in the handle function I am writing the whole scraping code. But should I suppose to do that? Or... what is the best approach for this?
UPDATED
If I understand correctly the answer below. It should look like this right now.
calling services
class siteControl extends Command
{
protected $signature = 'bot:scrape {website_id}';
protected $description = 'target a portal site and scrape';
public function __construct()
{
parent::__construct();
}
public function handle()
{
$website_id = $this->argument("website_id");
if ($website_id == 1) {
$portal = "App\Services\Site1";
}
$crawler = new $portal;
$crawler->run();
}
}
in handle method
class Site1 extends Utility
{
public function __construct()
{
parent::__construct();
}
public function run()
{
echo "method runs";
}
}
abstract:
use Goutte\Client;
abstract class Utility implements SiteInterfaces
{
protected $client;
public function __construct()
{
$this->client = new Client();
}
}
interfaces:
namespace App\Services;
interface SiteInterfaces
{
public function run();
}
and finally, I should write the whole scraping code inside the run() method? Please correct me If wrong about this... I am searching the best solution.
A best practice would be to call a separate service from your command handle() method. That way you could reuse that same service in a controller for instance.
The technical version:
Your application is given a specific thing to do (a command if you will). This command comes from outside of your application, which can be a anything from a web controller, to an API controller or a CLI application. In terms of hexagonal architecture this is called a port.
Once the application receives such a command it should not care which port it came from. By handling all similar commands in a single spot (a command handler) it does not have to worry about the origins of the command.
So to give you a short overview:
[Web request] [CLI command] <-- these are ports
\ /
\ /
\ /
[Command] <--- this is a method call to your service
|
|
|
[Command handler] <--- this is the service doing the actual work
Updated my answer
Based on the code you provided I implemented what I mentioned above like so:
app/Console/Command/BotScrapeCommand.php
This is the CLI command I mentioned above. All this class has to do is:
1. Gather input arguments; (website_id) in this case
2. Wrap those arguments in a command
3. Fire off the command using the command handler
namespace App\Console\Commands;
use App\Command\ScrapePortalSiteCommand;
use CommandHandler\ScrapePortalSiteCommandHandler;
class BotScrapeCommand extends Command
{
protected $signature = 'bot:scrape {website_id}';
protected $description = 'target a portal site and scrape';
public function handle(ScrapePortalSiteCommandHandler $handler)
{
$portalSiteId = $this->argument("website_id");
$command = new ScrapePortalSiteCommand($portalSiteId);
$handler->handle($command);
}
}
app/Command/ScapePortalSiteCommand.php
This is the Command I mentioned above. Its job is to wrap all input arguments in a class, which can be used by a command handler.
namespace App\Command;
class ScrapePortalSiteCommand
{
/**
* #var int
*/
private $portalSiteId;
public function __construct(int $portalSiteId)
{
$this->portalSiteId = $portalSiteId;
}
public function getPortalSiteId(): int
{
return $this->portalSiteId;
}
}
app/CommandHandler/ScrapePortalSiteCommandHandler.php
The command handler should implement logic based on its command. In this case that's figuring out which crawler to pick, then fire that one off.
namespace App\CommandHandler;
use App\Command\ScrapePortalSiteCommand;
use App\Crawler\PortalSite1Crawler;
use App\Crawler\PortalSiteCrawlerInterface;
use InvalidArgumentException;
class ScrapePortalSiteCommandHandler
{
public function handle(ScrapePortalSiteCommand $command): void
{
$crawler = $this->getCrawlerForPortalSite($command->getPortalSiteId());
$crawler->crawl();
}
private function getCrawlerForPortalSite(int $portalSiteId): PortalSiteCrawlerInterface {
switch ($portalSiteId) {
case 1:
return new PortalSite1Crawler();
default:
throw new InvalidArgumentException(
sprintf('No crawler configured for portal site with id "%s"', $portalSiteId)
);
}
}
}
app/Crawler/PortalSiteCrawlerInterface.php
This interface is there to make sure all crawlers can be called in similar fashion. Additionally it makes for nice type hinting.
namespace App\Crawler;
interface PortalSiteCrawlerInterface
{
public function crawl(): void;
}
app/Crawler/PortalSite1Crawler.php
This is where the implementation of the actual scraping goes.
namespace App\Crawler;
class PortalSite1Crawler implements PortalSiteCrawlerInterface
{
public function crawl(): void
{
// Crawl your site here
}
}
Another update
As you had some additional questions I've updated my answer once more.
:void
The use of : void in a method declaration means the method will not return anything. In a same way public function getPortalSiteId(): int means this method will always return an integer. The use of return typehints was added to PHP 7 and is not specific to Laravel. More information on return typehints can be found in the PHP documentation.
Commands and handlers
The use of commands and command handlers is a best practice which is part of the command bus pattern. This pattern describes an universal way of dealing with user input (a command). This post offers a nice explanation on commands and handlers. Additionally, this blog post describes in more details what a command bus is, how it's used and what the advantages are. Please note that in the code I've provided the bus implementation itself is skipped. In my opinion you do not need it per se, but in some cases it does add value.
This is my Laravel code but I think I might be using an older version of the Stripe function. That's why I'm getting this error, can anyone help me with this, please?
<?php
use Illuminate\Support\Facades\Cache;
use Stripe\Stripe;
class Plan
{
public static function getStripePlans()
{
// Set the API Key
Stripe::setApiKey(User::getStripeKey());
try {
// Fetch all the Plans and cache it
return Cache::remember('stripe.plans', 60 * 24, function () {
return \Stripe\Plan::all()->data;
});
} catch (\Exception $e) {
return false;
}
}
}
If you're using a version of the Stripe-PHP library < 2.0, you'd likely need to call Stripe_Plan::all() instead of \Stripe\Plan::all()
That said, it may be helpful to upgrade to a newer version of the Stripe PHP library to take advantage of more recent features https://github.com/stripe/stripe-php
I'm using Intellij to edit a play1 project. The project is build by command play new helloworld and play idealize helloworld
public class Application extends Controller {
public static void index() {
render();
}
}
Everything is OK except this error
render(Object...) in Controller cannot to be applied to ()
Any ideas?
Done!
File->Project Structure->Project->Project Language Level
Set it to an appropriate level, I set it to 9 and the problem is settled down :)