<?php global $wpdb; $table1 = $wpdb->prefix . "my_table"; if($wpdb->get_var( "show tables like '$table1'" ) != $table1) { $sql = "CREATE TABLE `". $table1 . "` ( "; $sql .= " `post_id` BIGINT NULL, "; $sql .= " `field1` VARCHAR(250) NULL, "; $sql .= " `field2` VARCHAR(250) NULL, "; $sql .= " INDEX `index_by_post_id` (`post_id`) "; $sql .= ") ENGINE=MyISAM DEFAULT CHARSET=latin1 ; "; require_once( ABSPATH . '/wp-admin/includes/upgrade.php' ); dbDelta($sql); } |
Sunday, February 17, 2019
Wordpress create table on Plugin activation if not exists
Friday, February 8, 2019
GRAILS > FUNCTIONALITY AFTER TRANSACTION COMMITTED
So the problem is when we working on grails project with hibernate transaction to manage data, we do not know when actually transaction committed or not. But sometimes we have to wait until current transaction finally committed. Because unless transaction committed, this data will not available for other transactions. Below is a sample project showing how to notified or when actually current transaction committed. Its some wired way but its working. |
THIS PROJECT FOR DEMONSTRATE HOW TO DO SOME ADDITIONAL WORK AFTER AN TRANSACTION COMMITED 1. First setup DataSource.groovy 2. Add *mavenRepo "https://oauth.googlecode.com/svn/code/maven"* in *repositories* to BuildConfig.groovy 3. Add below dependencies to *dependencies* in BuildConfig.groovy compile "org.springframework:spring-orm:$springVersion" runtime 'mysql:mysql-connector-java:5.1.29' runtime 'org.springframework:spring-test:4.0.5.RELEASE' 4. Add a controller named *HomeController.groovy* 5. Add a service named *HomeService.groovy* 6. Add a domain named *Home.groovy* MOST IMPORTANT PARTS: 7. Add below groovy files named *org.codehaus.groovy.grails.orm.hibernate.GrailsHibernateTransactionManager.groovy* named *org.codehaus.groovy.grails.orm.hibernate.TransactionStatus.groovy* named *org.codehaus.groovy.grails.orm.support.GrailsTransactionTemplate.groovy* under *src/groovy* 8. You are done! See *HomeService.groovy* to see how you can use this feature in Grails project. |
package org.codehaus.groovy.grails.orm.hibernate import groovy.transform.CompileDynamic import org.hibernate.FlushMode import org.springframework.orm.hibernate4.HibernateTransactionManager import org.springframework.transaction.TransactionDefinition import org.springframework.transaction.support.DefaultTransactionStatus class GrailsHibernateTransactionManager extends HibernateTransactionManager { @Override protected void doBegin(Object transaction, TransactionDefinition definition) { super.doBegin transaction, definition if (definition.isReadOnly()) { setFlushModeManual(transaction) } } @CompileDynamic protected void setFlushModeManual(transaction) { transaction.sessionHolder?.session?.flushMode = FlushMode.MANUAL } @Override protected DefaultTransactionStatus newTransactionStatus(TransactionDefinition definition, Object transaction, boolean newTransaction, boolean newSynchronization, boolean debug, Object suspendedResources) { return new TransactionStatus(super.newTransactionStatus(definition, transaction, newTransaction, newSynchronization, debug, suspendedResources)) } @Override protected void doCommit(DefaultTransactionStatus status) { super.doCommit(status) status.triggerCommitHandlers() } } |
BELOW IS SAMPLE OUTPUT |
package com.pritom import grails.transaction.Transactional import org.codehaus.groovy.grails.orm.hibernate.TransactionStatus @Transactional class HomeService { void saveEntity() { TransactionStatus.current.onCommit { println("YES!!! TRANSACTION COMMITTED SUCCESSFULLY!!!") println("HOME COUNT ${Home.count()}") } Home home = new Home() home.name = "House #${Home.count() + 1}" home.addreess = "Lane ${Home.count() + 1}, Dhaka" home.save() } } |
2019-02-08 11:33:55,048 [http-bio-8080-exec-1] DEBUG hibernate.SQL - select count(*) as y0_ from home this_ Hibernate: select count(*) as y0_ from home this_ 2019-02-08 11:33:55,050 [http-bio-8080-exec-1] DEBUG hibernate.SQL - select count(*) as y0_ from home this_ Hibernate: select count(*) as y0_ from home this_ 2019-02-08 11:33:55,053 [http-bio-8080-exec-1] DEBUG hibernate.SQL - insert into home (version, addreess, name) values (?, ?, ?) Hibernate: insert into home (version, addreess, name) values (?, ?, ?) 2019-02-08 11:33:55,054 [http-bio-8080-exec-1] TRACE sql.BasicBinder - binding parameter [1] as [BIGINT] - [0] 2019-02-08 11:33:55,054 [http-bio-8080-exec-1] TRACE sql.BasicBinder - binding parameter [2] as [VARCHAR] - [Lane 5, Dhaka] 2019-02-08 11:33:55,054 [http-bio-8080-exec-1] TRACE sql.BasicBinder - binding parameter [3] as [VARCHAR] - [House #5] YES!!! TRANSACTION COMMITTED SUCCESSFULLY!!! 2019-02-08 11:33:55,130 [http-bio-8080-exec-1] DEBUG hibernate.SQL - select count(*) as y0_ from home this_ Hibernate: select count(*) as y0_ from home this_ HOME COUNT 5 |
You can use multiple TransactionStatus.current.onCommit, each will be called one after one. |
You can download sample project from here |
GitHub project link |
Required JAR file to get this working (if dependecny failed) |
GRAILS : Rendering Groovy GSP Code From A String | Grails – Rendering a Template from a String | Render Grails template from external source
package com.pkm.utils import grails.util.Holders import groovy.text.Template import org.codehaus.groovy.grails.web.pages.GroovyPagesTemplateEngine import org.springframework.core.io.ByteArrayResource import org.springframework.web.context.request.RequestContextHolder /** * Created by pritom on 29/11/2017. */ class InvoicePdfUtils extends UtilsBase { static def test() { GroovyPagesTemplateEngine engine = Holders.applicationContext.getBean(GroovyPagesTemplateEngine) StringWriter stringWriter = new StringWriter() String content = "CONTENT-\${a}--\${b.none?.none ?: 'None'}-MINE-XXX " + "<ui:serverURL/> <g:if test='true'>True</g:if> HERE??? YES ME IS HERE, ".toString() Map model = [a: '10', b: [:]] String pageName = engine.getCurrentRequestUri(RequestContextHolder.getRequestAttributes().request) // /grails/test.dispatch Template template = engine.createTemplate(new ByteArrayResource(content.getBytes("UTF-8"), pageName), pageName, true) Writable renderedTemplate = template.make(model) renderedTemplate.writeTo(stringWriter) println("Request-path=${engine.getCurrentRequestUri(RequestContextHolder.getRequestAttributes().request)}") println(stringWriter.toString()) } }
This code block will take input from yourself and then parse as a GSP parser and return output as String.
https://little418.com/2009/11/rendering-groovy-gsp-code-from-a-string.html
Try catch not working Laravel raw queries | How to properly catch PHP exceptions (Laravel 5.X) | Why try catch not work in Laravel
Make sure you're using your namespaces properly. If you use a class without providing its namespace, PHP looks for the class in the current namespace. Exception class exists in global namespace, so if you do that try/catch in some namespaced code, e.g. your controller or model, you'll need to do catch(\Exception $e) to catch all your exceptions:
try { //code causing exception to be thrown } catch(\Exception $e) { //exception handling }
If you do it like this there is no way to miss any exceptions. Otherwise if you get an exception in a controller code that is stored in App\Http\Controllers, your catch will wait for App\Http\Controllers\Exception object to be thrown.
Laravel 5 Check if request is ajax request | Ajax request validation
<?php use Illuminate\Support\Facades\Request; return Request::ajax(); /* True | False */
Getting url() in a Command returns http://localhost | URL generated in a queue - localhost returned | URL in jobs only return localhost | URL problem with queued jobs
First need to specify url to project/config/app.php as below:
Now need to modify project/app/Providers/RouteServiceProvider.php as below:
<?php return [ 'url' => 'http://localhost:81/my_laravel_project/' ];
Now need to modify project/app/Providers/RouteServiceProvider.php as below:
<?php namespace App\Providers; use Illuminate\Routing\Router; use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider; class RouteServiceProvider extends ServiceProvider { /** * This namespace is applied to the controller routes in your routes file. * * In addition, it is set as the URL generator's root namespace. * * @var string */ protected $namespace = 'App\Http\Controllers'; /** * Define your route model bindings, pattern filters, etc. * * @param \Illuminate\Routing\Router $router * @return void */ public function boot(Router $router) { parent::boot($router); $url = $this->app['url']; $url->forceRootUrl(config('app.url')); } /** * Define the routes for the application. * * @param \Illuminate\Routing\Router $router * @return void */ public function map(Router $router) { $router->group(['namespace' => $this->namespace], function ($router) { require app_path('Http/routes.php'); }); } }
Using custom monolog handlers in Laravel
You can easily add new handlers to Monolog
$manage_monolog = function(\Monolog\Logger $monolog) { #New monolog file name $filename = storage_path('logs'.DIRECTORY_SEPARATOR.'custom.log'); $handler = new \Monolog\Handler\RotatingFileHandler($filename); #If you only keep this handler only $monolog->setHandlers(array($handler)); #If you need to add this custom handler to existing handlers $monolog->pushHandler($handler); print_r($monolog->getHandlers()); }; $manage_monolog(\Illuminate\Support\Facades\Log::getMonolog()); \Illuminate\Support\Facades\Log::info("Its completed...");
Subscribe to:
Posts (Atom)